Reverse the word of the statement
Description :
Normally we reverse the string.
But the following program is used to reverse the word of the statement.
Code Segment
string s1 = "One Two Three Four Five Six";
int index;
index=s1.LastIndexOf(" ");
string s2 = s1.Substring(index+1);
s1 = s1.Substring(0,index);
index = s1.LastIndexOf(" ");
string s3 = s1.Substring(index+1);
s1 = s1.Substring(0,index);
index = s1.LastIndexOf(" ");
string s4 = s1.Substring(index+1);
s1 = s1.Substring(0,index);
index = s1.LastIndexOf(" ");
string s5 = s1.Substring(index+1);
Console.WriteLine ("s2: {0}\ns3: {1}",s2,s3);
Console.WriteLine ("s4: {0}\ns5: {1}\n",s4,s5);
Console.WriteLine ("s1: {0}\n",s1);
Output
Six
Five
Four
Three
Two
One
Code Explanation
1. get the index of the last space
2. get the last word.
3. set s1 to the substring starting at 0 and ending at index (the start of the last word thus s1 has one two three
4. find the last space in s1 (after two)
5. set s3 to the substring starting at index, the space after "two" plus one more thus s3 = "three"
6. reset s1 to the substring starting at 0 and ending at index, thus the string "one two"
7. reset index to the space between "one" and "two"
8. set s4 to the substring starting one space after index, thus the substring "two"
9. reset s1 to the substring starting at 0 and ending at index, thus "one"
10. set index to the last space, but there is none so index now = -1
11. set s5 to the substring at one past the last space. there was no last space so this sets s5 to the substring starting at zero