2

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);
                        
            }
        }
    }
Alenros
  • 816
  • 7
  • 23
PatraS
  • 21
  • 2
  • 2
    If you have unicode characters, consider https://stackoverflow.com/questions/15029238/reverse-a-string-with-accent-chars – Martheen Jan 18 '21 at 04:47
  • Does this answer your question? [Easy way to reverse each word in a sentence](https://stackoverflow.com/questions/5391198/easy-way-to-reverse-each-word-in-a-sentence) – Callum Watkins Jan 18 '21 at 05:12
  • and then somebody mentions that Chinese is written without spaces, making the notion of words vs characters rather moot... – Marc Gravell Jan 18 '21 at 09:52

3 Answers3

6

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()));
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
0
    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);
    }
bingbing
  • 1
  • 4
0

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 Reversed 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!
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215