Reputation: 1711
In the below code, I am getting the StringIndexOutOfBoundsException
in sBuilder.insert(pos,words[i]);
line,
I have initialized the length here new StringBuilder(s.length())
for the below input,
System.out.println(sortSentence("is2 sentence4 This1 a3"));
public static String sortSentence(String s) {
StringBuilder sBuilder=new StringBuilder(s.length());
String words[]= s.split(" ");
for(int i=0;i<words.length;i++)
{
int pos= Integer.parseInt(words[i].replaceAll("\\D+",""));
// this is the line of error
sBuilder.insert(pos,words[i]);
}
return sBuilder.toString();
}
This is the error I am getting,
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: offset 2, length 0
The length of the input String is 22 how can I get this error despite of this ?
Upvotes: 0
Views: 600
Reputation: 5557
What I understand that you are simply trying to remove spaces. I may suggest to go for much simpler approach. No need to start with capacity at all.
public class MyClass {
public static String sortSentence(String s) {
StringBuilder sBuilder=new StringBuilder();
String words[]= s.split(" ");
for(int i=0;i<words.length;i++)
{
int pos= Integer.parseInt(words[i].replaceAll("\\D+",""));
// this is the line of error
sBuilder.append(words[i]);
}
return sBuilder.toString();
}
public static void main(String args[]) {
System.out.println(sortSentence("is2 sentence4 This1 a3"));
}
}
OR
Simply use String replaceAll()
method.
Upvotes: 0
Reputation: 3205
If you check the code where the exception is raised it becomes clearer. StringBuilder's content has no such index, and the capacity from the constructor doesn't fill it by default.
static void checkOffset(int offset, int length) {
if (offset < 0 || offset > length) {
throw new StringIndexOutOfBoundsException("offset " + offset +
", length " + length);
}
}
Also the javadoc says it:
Inserts the string representation of the Object argument into this character sequence. The offset argument must be greater than or equal to 0, and less than or equal to the length of this sequence. Throws: StringIndexOutOfBoundsException – if the offset is invalid.
Note: length, not capacity, of StringBuilder, not of the input string.
For the notion that sBuilder.setLength(s.length());
solves the problem: only if the perceived problem is the exception alone. setLength
initializes the internally used array with (byte)0
btw, which gives a rather odd string as a result.
But then, why use a string builder in the first place? Just set everything in the original string to " " which is not an integer, can be done with a single regex like this one: s.replaceAll("[^0-9]", " ")
.
Or the other way: don't insert into stringbuilder, just append, solves the problem too, maybe, depending on the interpretation.
Looks like the whole issue belongs more on a code review site, imho.
Upvotes: 2