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

output

I have attached the class file also for reference.