title:Reverse Words in a string
Given an input string, reverse the string word by word.
For example,
Given s = " the sky is blue
",
Return " blue is sky the
".
parsing: outputting words in a string in reverse order
With the help of a stack, the string was traversed backwards, encountered empty, skipped until non-empty characters, stitched word, and so on again encountered empty, get a word, add a stack,
And so on until the last character of S is traversed.
Finally, the word in the stack is output in turn
Java Encoding:
Method One:
Public String reversewords (string s) {if (s = = NULL | | s.length () = = 0) return s; int index = 0; //The pointer to traverse int len = S.length (); stack<string> stack = new stack<string> (); Stack, advanced out, sequential save word, reverse output StringBuilder Sbuilder = new StringBuilder (); Record each word char[] characters = S.tochararray (); while (Index < len) {//traversal string for (; index < len && Characters[index] = = "; ++index);//Skip NULL characters for (; index < len && Characters[index]! = "; ++index) {//Stitching word sbuilder.append (characters[ Index]); } if (Sbuilder.length () > 0) {//to press a valid word into the stack Stack.push (sbuilder.tostring ()); Sbuilder.delete (0,sbuilder.length ());//Empty StringBuilder}} sbuilder.delete (0,sbuilder.len Gth ());//Empty StringBuilder while (Stack.size () > 1) {//Not last word, output, plus space Sbuilder.append (stack.pop () + " "); if (stack.size () = = 1)//The last word, output, no spaces, here to determine whether the stack is empty, because the possible input string is empty sbuilder.append (Stack.pop ()); return sbuilder.tostring (); }
Method Two:
The regular expression, \s, represents a space, + represents at least one space, so that multiple spaces separated by Word can be extracted.
Public String reversewords (string s) { string[] words = S.split ("\\s+"); Regular expression StringBuffer sb = new StringBuffer (); for (int i = words.length-1; I >= 0; i.) { sb.append (Words[i] + ""); } Return sb.tostring (). Trim (); }
Reverse words in a string (Java note some detail handling)