简体   繁体   中英

C#: Reverse the words in sentence

Below code if for reverse word in a sentence, the word sequence in the sentence will be same but the word will be reversed

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

For simple text, you can just use Split , Reverse , Concat and Join

var words = Console.ReadLine()
     .Split()
     .Select(x => string.Concat(x.Reverse()));

Console.WriteLine(string.Join(" ", words));

Output

Enter a string: asd sdf dfg fgh
dsa fds gfd hgf

For complicated Unicode, you will need to be more precise in the grouping of characters. However, you can take advantage of GetTextElementEnumerator

Returns an enumerator that iterates through the text elements of a string.

Given

public static IEnumerable<string> ToElements(this string source)
{
   var enumerator = StringInfo.GetTextElementEnumerator(source);
   while (enumerator.MoveNext())
      yield return enumerator.GetTextElement();
}

Usage

var words = Console.ReadLine()
   .Split()
   .Select(x => string.Concat(x.ToElements().Reverse()));
    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);
    }

Let's start from definition ; assuming that

Word is a non-empty sequence of letters and apostrophes

we can implement a simple solution with a help of regular expressions (and a pinch of Linq - Reverse() ): all we have to do is to Replace each word with its Reverse d representation.

Code:

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

  ...

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

Demo:

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

Outcome:

Text (на русском)              => txeT (ан мокссур)
Simple test.                   => elpmiS tset.
Another "text": punctuation!   => rehtonA "txet": noitautcnup!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM