I am trying to reverse the location of words in a string which i have working but not sure if it's the best way. I can't use Array.Reverse or String.Split in the code. The idea is to return a string with the words reversed. eg: “The quick brown fox” should return “fox brown quick The”
Is it better to use stringbuilder for both operations for efficiency. Shall I cast the input string to a stringbuilder?
Not sure if using a "while string not null" test is a good idea in the while loop. Also I would like to keep this to just 1 function answer.
Code:
public string ReverseWordsInString (string input) { StringBuilder result = new StringBuilder(); //remove all potentially multiple whitespace from beginning //and end of string so indexof test does not match empty whitespace input = input.Trim(); //next insert a single blank space at the end of the string //to satisfy the last indexOf test. input = input.Insert((input.Length), " "); while(input != "") { //find location of whitespace to identify end of word int t = input.IndexOf(" "); //input the word into result string (use t + 1 to include the space) result.Insert( 0, (input.Substring(0 , (t + 1)))); //removed the word just retrieved for the next loop input = input.Remove(0, (t + 1)); t = 0; } return result.ToString(); }
Is it better to use stringbuilder for both operations for efficiency. Shall I cast the input string to a stringbuilder?
Not sure if using a "while string not null" test is a good idea in the while loop. Also I would like to keep this to just 1 function answer.
Comment