Skip to content

Instantly share code, notes, and snippets.

@danlamanna
Created December 21, 2014 00:40
Show Gist options
  • Save danlamanna/cc497aa841ef4d70fafc to your computer and use it in GitHub Desktop.
Save danlamanna/cc497aa841ef4d70fafc to your computer and use it in GitHub Desktop.
import java.lang.StringBuilder;
class ReverseWords {
public static String reverse_words(String str) {
StringBuilder reversed = new StringBuilder();
int last = 0;
for (int i=0;i<str.length(); i++) {
if (str.charAt(i) == ' ') {
reversed.insert(0, str.substring(last, i));
reversed.insert(0, " ");
last = i+1;
}
}
reversed.insert(0, str.substring(last));
return reversed.toString();
}
public static void main(String[] args) {
String str = "My name is Chris";
System.out.println(str);
System.out.println(reverse_words(str));
str = "My name is Chris";
System.out.println(str);
System.out.println(reverse_words(str));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment