C#:反转句子中的单词

标签 c#

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

    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 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/

相关文章:

c# - 为什么我的线程不会停止?

c# - 如何从 Kinect 深度数组中获取位置 (x,y)?

c# - 在运行时添加控件的最佳实践

c# - 无法在 Visual Studio 2019 中将 LocBaml 与 WPF .Net 5.0 项目一起使用

c# - 从 aspx 网页读取 xml

c# - 以编程方式附加数据库

c# - 关于C#中Dispose()和析构函数的两个问题

c# - 从 txt 文件中读取每一行作为数组

c# - 我想在关闭我的 UWP 应用程序之前存储一个 int 值

c# - Windows 模拟和复制 token