Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Reverse the words in sentence

Tags:

c#

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);
                        
            }
        }
    }
like image 900
PatraS Avatar asked Nov 24 '25 21:11

PatraS


1 Answers

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()));
like image 68
TheGeneral Avatar answered Nov 26 '25 11:11

TheGeneral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!