C#:反转句子中的单词

C#: Reverse the words in sentence

提问人:PatraS 提问时间:1/18/2021 最后编辑:AlenrosPatraS 更新时间:10/28/2023 访问量:251

问:

下面的代码如果对于句子中的反向单词,则句子中的单词序列将相同,但单词将被颠倒

    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);
                        
            }
        }
    }
c#

评论

2赞 Martheen 1/18/2021
如果您有 unicode 字符,请考虑 stackoverflow.com/questions/15029238/...
0赞 Callum Watkins 1/18/2021
这回答了你的问题吗?颠倒句子中每个单词的简单方法
0赞 Marc Gravell 1/18/2021
然后有人提到中文是没有空格的,这使得单词与字符的概念变得毫无意义......

答:

6赞 TheGeneral 1/18/2021 #1

对于简单的文本,您只需使用 SplitReverseConcatJoin

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

返回一个枚举器,该枚举器循环访问 字符串。

鉴于

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()));
0赞 bingbing 1/18/2021 #2
    static void Main(string[] args)
    {
        //method 1
        Console.Write("Enter a string: ");
        string sentence = Console.ReadLine();
        string[] words = sentence.Split(" ");
        StringBuilder destination = new StringBuilder(); //Sentence reverse
        foreach (string word in words)
        {
            destination.Append(string.Concat(new string(word.Reverse().ToArray()), " "));
        }
        Console.WriteLine(destination);

        //method 2 but need import System.Linq namespace.
        var reversedWords = string.Join(" ", sentence.Split(' ').Select(x => new String(x.Reverse().ToArray())));
        Console.WriteLine(reversedWords);
    }
0赞 Dmitry Bychenko 1/18/2021 #3

让我们从定义开始;假设

单词字母撇号的非空序列

我们可以借助正则表达式(以及一小撮 Linq - )实现一个简单的解决方案:我们所要做的就是对每个单词的 d 表示。Reverse()ReplaceReverse

法典:

  using System.Linq;
  using System.Text.RegularExpressions;

  ...

  private static string WordReverse(string value) => 
    Regex.Replace(value ?? "", @"[\p{L}_]+", m => string.Concat(m.Value.Reverse()));

演示:

  string[] tests = new string[] {
    "Text (на русском)",
    "Simple test.",
    "Another \"text\": punctuation!"
  };
 
  Console.Write(string.Join(Environment.NewLine, tests
    .Select(test => $"{test,-30} => {WordReverse(test)}")));

结果:

Text (на русском)              => txeT (ан мокссур)
Simple test.                   => elpmiS tset.
Another "text": punctuation!   => rehtonA "txet": noitautcnup!
0赞 RPA HEM 10/28/2023 #4
//Without Using split, Concat and reverse inbuilt method of C# - 

int count = 0;
string s = Console.ReadLine();
char[] ch = s.ToCharArray();
for(int i= ch.Length-1; i>=0; i--)
            {
                if (ch[i] != ' ')
                {
                    count++;
                }
                else if (ch[i] == ' ')
                {
                    for(int j=i+1; count>0; j++)
                    {
                        Console.Write(ch[j]);
                        count--;
                    }
                    Console.Write(" ");
                }
            }

            for (int j = 0; j <= count; j++)
            {
                Console.WriteLine(ch[j]);
            }
            Console.ReadLine();