Reverse Each Word in a Sentence without using any Function/String Variables in C#

Let say, input character array is “This is a good day”. I need the output as “sihT si a doog yad”.

Logic:

To do this, first we have to fetch the each word from the sentence based on the space and then swap the character in the word.

Code:

  1. string sentense = "This is a good day";  
  2. char[] arr = sentense.ToCharArray();  
  3. int temp = 0;  
  4.   
  5. //Logic to iterate up to end of the line.  
  6. for (int fl = 0; fl <= arr.Length - 1;fl++ )  
  7. {  
  8.     int count = temp;  
  9.     int num1 = 1;  
  10.     //To get the word before space or the last word  
  11.     if (arr[fl] == ' ' || fl == arr.Length - 1)  
  12.     {  
  13.         if (fl == arr.Length - 1)  
  14.         {  
  15.             for (int c = fl; c >= temp; c--)  
  16.             {  
  17.                 //Swap the word  
  18.                 if (num1 <= (fl - temp) / 2)  
  19.                 {  
  20.                     char tempC = arr[count];  
  21.                     arr[count] = arr[c];  
  22.                     arr[c] = tempC;  
  23.                     count++;  
  24.                     num1++;  
  25.                 }  
  26.             }  
  27.         }  
  28.         else  
  29.         {  
  30.             for (int c = fl - 1; c >= temp; c--)  
  31.             {  
  32.   
  33.                 if (num1 <= (fl - temp) / 2)  
  34.                 {  
  35.                     char tempC = arr[count];  
  36.                     arr[count] = arr[c];  
  37.                     arr[c] = tempC;  
  38.                     count++;  
  39.                     num1++;  
  40.                 }  
  41.             }  
  42.         }  
  43.         temp = fl + 1;                  
  44.     }  
  45.   
  46. }  
  47.   
  48. string newLine = new string(arr);     
Output:

output

I have attached the class file also for reference.

Ebook Download
View all
Learn
View all