PatraS
PatraS

Reputation: 31

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

Upvotes: 3

Views: 334

Answers (4)

RPA HEM
RPA HEM

Reputation: 1

//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();

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186698

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!

Upvotes: 0

TheGeneral
TheGeneral

Reputation: 81503

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

Upvotes: 6

bingbing
bingbing

Reputation: 1

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

Upvotes: 0

Related Questions