Reverse string with word in Java
•
Java
I have the following code to reverse the string word by word, but I have a question. First, can someone point out how to make it better? Second, how to delete the space I finally get 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;
}
Now the phrase becomes:
Notice the space at the beginning of the new string
Solution
Without using the split function, the code looks 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);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
