Reverse individual words in a Java String -
i trying reverse text in given string. problem having code below when enter "hey man" prints out "nam yeh" whereas want print out "yeh nam". there give me fix mistake?
thanks in advance!
public class reversewords { public static void main(string[] args) { string text; text = io.readstring(); int plusindex = text.indexof("+"); if ( plusindex != -1 ) { io.reportbadinput(); system.exit(0); } io.outputstringanswer(new stringbuilder(text).reverse().tostring()); } }
split input on space character, loop through array of words, reverse them, , piece them new string.
private string reversewords(string text) { string result = ""; string[] words = text.split(" "); stringbuilder builder; (string word : words) { builder = new stringbuilder(word); result = result + " " + builder.reverse().tostring(); ) return result.replacefirst(" ", ""); } reversewords("hey man"); //should return "yeh nam"
Comments
Post a Comment