下面的代码如果对于句子中的单词倒序,句子中的单词序列相同但单词会被反转
using System;
using System.Text;
namespace reverse_a_string
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a string: ");
string S = Console.ReadLine();
string[] sep = S.Split(" ");
StringBuilder Wrev = new StringBuilder(); //Word reverse
StringBuilder Srev = new StringBuilder(); //Sentence reverse
for (int j=0;j<sep.Length;j++)
{
for (int i = sep[j].Length - 1; i >= 0; i--)
{
Wrev.Append(sep[j][i]);
}
Srev.Append(Wrev);
Wrev.Clear();
Wrev.Append(" ");
}
Console.WriteLine(Srev);
}
}
}
最佳答案
对于简单的文本,你可以使用Split
, Reverse
, Concat
和 Join
var words = Console.ReadLine()
.Split()
.Select(x => string.Concat(x.Reverse()));
Console.WriteLine(string.Join(" ", words));
输出
Enter a string: asd sdf dfg fgh
dsa fds gfd hgf
对于复杂的 Unicode,您需要在字符分组上更加精确。但是,您可以利用 GetTextElementEnumerator
Returns an enumerator that iterates through the text elements of a string.
给定
public static IEnumerable<string> ToElements(this string source)
{
var enumerator = StringInfo.GetTextElementEnumerator(source);
while (enumerator.MoveNext())
yield return enumerator.GetTextElement();
}
用法
var words = Console.ReadLine()
.Split()
.Select(x => string.Concat(x.ToElements().Reverse()));
关于C#:反转句子中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65768922/