给定一个字符串
"hello there, compiler."
如何颠倒每个单词,除了标点符号。所以完成后将打印:
"olleh ereht, relipmoc."
而不是 “olleh ,ereht .relipmoc”
我的代码(忽略标点符号):
static string ReverseString(string s)
{
StringBuilder sb = new StringBuilder();
string[] words = s.Split(' ');
foreach (var word in words)
{
for (int i = word.Length - 1; i >= 0; i--)
{
sb.Append(word[i]);
}
sb.Append(" ");
}
return sb.ToString();
}
最佳答案
我建议 Split
(技巧:不仅在空格上,而且在非单词符号上——空格、逗号、点等),修改和最终 Concat
:
using using System.Text.RegularExpressions;
...
string source = @"hello there, compiler.";
string result = string.Concat(Regex
.Split(source, @"(\W+)") // split on not word letter, separator preserved
.Select(letter => letter.Length > 0 && char.IsLetter(letter[0])
? string.Concat(letter.Reverse()) // reverse letter
: letter)); // keep separator intact
Console.Write(result);
结果:
olleh ereht, relipmoc.
关于c# - 反转字符串中的单词,标点符号除外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45079955/