How to reverse a given string word by word instead of letters using C#?


Create a method reverse Words that takes char array as an input and for each and every character until the empty space is not reached reverse the word. At the last step reverse the entire string from length 0 to n-1 length. In the first step the string “This is my book” will be turned into “koob ym si siht”. At the end of the second step the string words will be reversed to “book my is This”

Time complexity − O(N)

Example

 Live Demo

using System;
namespace ConsoleApplication{
   public class Arrays{
      static void reverse(char[] str, int start, int end){
         char temp;
         while (start <= end){
            temp = str[start];
            str[start] = str[end];
            str[end] = temp;
            start++;
            end--;
         }
      }
      public char[] reverseWords(char[] s){
         int start = 0;
         for (int end = 0; end < s.Length; end++){
            if (s[end] == ' '){
               reverse(s, start, end);
               start = end + 1;
            }
         }
         reverse(s, 0, s.Length - 1);
         return s;
      }
   }
   class Program{
      static void Main(string[] args){
         Arrays a = new Arrays();
         string s = " This is my book ";
         var res = a.reverseWords(s.ToCharArray());
         Console.WriteLine(new String(res));
         Console.ReadLine();
      }
   }
}

Output

book my is This

Updated on: 27-Aug-2021

165 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements