gpt4 book ai didi

C#:反转句子中的单词

转载 作者:行者123 更新时间:2023-12-02 16:19:47 24 4
gpt4 key购买 nike

下面的代码如果对于句子中的单词倒序,句子中的单词序列相同但单词会被反转

    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 , ConcatJoin

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 astring.

给定

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com