.net 替换词

pexxcrt2  于 2022-12-20  发布在  .NET
关注(0)|答案(2)|浏览(94)

我想替换我在控制台中键入的句子的第一个单词和最后一个单词。
如果我在控制台中键入以下语句:

London is the Capital of UK.

我需要这样的结果

UK is the capital of London.
yi0zb3m4

yi0zb3m41#

您可以使用以下方法和String.Split + String.Join

public static void SwapFirstAndLast<T>(IList<T>? items)
{
    if (items == null || items.Count < 2) return;
    T first = items[0];
    items[0] = items.Last();
    items[^1] = first;
}
string sentence = " London is the Capital of UK";
string[] wordDelimiters = { " " };
string[] words = sentence.Trim().Split(wordDelimiters, StringSplitOptions.RemoveEmptyEntries);
SwapFirstAndLast(words);
sentence = string.Join(" ", words);
dwbf0jvd

dwbf0jvd2#

在更一般的情况下,我们应该考虑标点符号,例如。

London, being a vast area, is the capital of UK =>

=> UK, being a vast area, is the capital of London

我们可以使用正则表达式来匹配单词。假设单词是字母和撇号的序列,我们可以使用

[\p{L}']+

阵列并执行以下操作:

using System.Text.RegularExpressions;

...

string text = "London, being a vast area, is the capital of UK";

// All words matched
var words = Regex.Matches(text, @"[\p{L}']+");

// Replace matches: first into last, 
// last into first, all the others keep intact
int index = -1;

var result = Regex.Replace(
    text,
  @"[\p{L}']+",
    m => {
       index += 1;

       if (index == 0)
         return words[^1].Value;
       if (index == words.Count - 1)
         return words[0].Value;
       return m.Value;
    });
``

相关问题