'How do I reverse a string in java by creating a new temporary string?
What's the error in the following code? I am not able to identify it shows the index 0 out of bounds exception.
public class stringBuilders{
public static void main(String[] args)
{
StringBuilder str = new StringBuilder("Shubham");
StringBuilder str2= new StringBuilder();
int j=0;
for(int i = str.length()-1; i>=0 ; i--)
{
str2.setCharAt(j++,str.charAt(i));
}
System.out.print(str2);
}
}
Solution 1:[1]
As you are already iterating from end to start you can just append the characters to the fresh and empty string builder. setChar()
is only intended to replace existing characters.
public class StringBuilders {
public static void main(String[] args) {
String str = "Shubham";
StringBuilder str2 = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
str2.append(str.charAt(i));
}
System.out.println(str2.toString());
}
}
gives
$ java StringBuilders.java
mahbuhS
Solution 2:[2]
You haven't declared a value to the str2
string.
The for loop is trying to find a character at index j=0
in str2
to set value i
of str2
, which it cannot find.
Hence the error.
For this to work, you need declare a value of str2 to a length >= str1. i.e., if str1 = "0123456"
, str2 should be at least 0123456
or more.
Instead of using StringBuilder
to set the char
, you can use String
to just append to it.
String str1 = new String("Shubham");
String str2 = new String();
int iter = str1.length() -1;
for(int i=iter; i>=0; i--) {
str2 += str1.charAt(i);
}
System.out.println(str2)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Chirag |