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;
-
-
- for (int fl = 0; fl <= arr.Length - 1;fl++ )
- {
- int count = temp;
- int num1 = 1;
-
- if (arr[fl] == ' ' || fl == arr.Length - 1)
- {
- if (fl == arr.Length - 1)
- {
- for (int c = fl; c >= temp; c--)
- {
-
- 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);
Output:
I have attached the class file also for reference.