I have the following code to reverse a string word by word, I have a question though, first could anyone point at how to make it better code? and second, how can I remove the space that I end up with at the beginning of the new string.
String str = "hello brave new world";
tStr.reverseWordByWord(str)
public String reverseWordByWord(String str){
int strLeng = str.length()-1;
String reverse = "", temp = "";
for(int i = 0; i <= strLeng; i++){
temp += str.charAt(i);
if((str.charAt(i) == ' ') || (i == strLeng)){
for(int j = temp.length()-1; j >= 0; j--){
reverse += temp.charAt(j);
if((j == 0) && (i != strLeng))
reverse += " ";
}
temp = "";
}
}
return reverse;
}
the phrase at the moment becomes:
olleh evarb wen dlrow
notice the space at the beginning of the new string.
Not using the split function the code would look like:
public static void reverseSentance(String str) {
StringBuilder revStr = new StringBuilder("");
int end = str.length(); // substring takes the end index -1
int counter = str.length()-1;
for (int i = str.length()-1; i >= 0; i--) {
if (str.charAt(i) == ' ' || i == 0) {
if (i != 0) {
revStr.append(str.substring(i+1, end));
revStr.append(" ");
}
else {
revStr.append(str.substring(i,end));
}
end = counter;
}
counter--;
}
System.out.println(revStr);
}
If str = "The quick brown fox jumped over the lazy dog!" it will return it like "dog! lazy the over jumped fox brown quick The" ...
private static String Reverse(String str) {
char charArray[] = str.toCharArray();
for (int i = 0; i <str.length(); i++){
if(charArray[i] == ' ')
return Reverse(str.substring(i + 1)) + str.substring(0, i) + " ";
}
return str + " ";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With