Returning a word of a string
I want to flip words to String. I tried to implement it like this:
public String reverseWords(String str) {
String reverse = "";
String[] arr = str.split(" ");
for (int i = arr.length; i < 0; i++) {
reverse+=arr[i];
}
return reverse;
}
However, does this return nothing to me? Any guidance on what I am doing wrong?
+3
source to share
6 answers
You need to repeat the loop back. using --
and you don't have to go from 0 to length
, but from length
to 1
. This is the basic logic behind the manual reverse function.
try this:
public static String reverseWords(String str) {
StringBuilder sb = new StringBuilder(str.length() + 1);
String[] words = str.split(" ");
for (int i = words.length - 1; i >= 0; i--) {
sb.append(words[i]).append(' ');
}
sb.setLength(sb.length() - 1); // Strip trailing space
return sb.toString();
}
+3
source to share
if you want to use a loop.
version 1:
public String reverseWords(String str) {
String reverse = "";
for (int i = str.length()-1; i >= 0; i--) {
reverse+=str.charAt(i);
}
return reverse;
}
version 2:
public String reverseWords(String str) {
StringBuilder sb = new StringBuilder(str.length()+1);
for (int i = str.length()-1; i >= 0; i--) {
sb.append(str.charAt(i));
}
return sb.toString();
}
+2
source to share