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:
- string sentense = "This is a good day";
- char[] arr = sentense.ToCharArray();
- int temp = 0;
- //Logic to iterate up to end of the line.
- for (int fl = 0; fl <= arr.Length - 1;fl++ )
- {
- int count = temp;
- int num1 = 1;
- //To get the word before space or the last word
- if (arr[fl] == ' ' || fl == arr.Length - 1)
- {
- if (fl == arr.Length - 1)
- {
- for (int c = fl; c >= temp; c--)
- {
- //Swap the word
- if (num1 <= (fl - temp) / 2)
- {
- char tempC = arr[count];
- arr[count] = arr[c];
- arr[c] = tempC;
- count++;
- num1++;
- }
- }
- }
- else
- {
- for (int c = fl - 1; c >= temp; c--)
- {
- if (num1 <= (fl - temp) / 2)
- {
- char tempC = arr[count];
- arr[count] = arr[c];
- arr[c] = tempC;
- count++;
- num1++;
- }
- }
- }
- temp = fl + 1;
- }
- }
- string newLine = new string(arr);

I have attached the class file also for reference.

Amarkant SemwalPosted Sep 19, 2023, 5:03 PM
We can do same thing with below snip string sentense = "This is a good day"; string container = string.Empty; string[] arr = sentense.Split(' '); for (int i = 0; i < arr.Length; i++) { string word = arr[i]; int len = arr[i].Length - 1; while (len >= 0) { container = container + word[len]; len--; } container = container + " "; } Console.WriteLine(container); Console.ReadKey();
Hari AmaraPosted Feb 13, 2020, 8:04 AM
Simple method will send me the
SeenuPosted May 30, 2017, 6:44 AM
I need to give input dynamically any sentence,above code not working
venkat rongalaPosted Jul 28, 2015, 8:29 PM
it doesn't wotk with 2 letter word
dana danaPosted Dec 5, 2014, 7:40 AM
nice idea :)