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);
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;
});
``
2条答案
按热度按时间yi0zb3m41#
您可以使用以下方法和
String.Split
+String.Join
:dwbf0jvd2#
在更一般的情况下,我们应该考虑标点符号,例如。
我们可以使用正则表达式来匹配单词。假设单词是字母和撇号的序列,我们可以使用
阵列并执行以下操作: