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?
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();
}
try i=0
before arr.length
or i--
and i>=0
.
Or in more detail:
Do you want to
for (int i=arr.length-1 ; i>=0 ;i--)
You have:
for (int i = arr.length; i < 0; i++) {
I will always be greater than or equal to 0 if it is length.
Try it:
for (int i = arr.length; i > 0; i--) {
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();
}
if the string is huge, moreover, if you are in a multi-threaded environment, it is recommended to use StringBuffer instead of StringBuilder.
public String reverseWords(String str) {
return new StringBuffer(str).reverse().toString();
}
I am giving another option for changing the string using charArray in java. 1. copy the whole string to char array using function 2. Just print the character in reverse order.