Click here to Skip to main content
14,700,108 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
String s2="samples"; Delete either of s character from a value of s2 string variable???

pls resolve this 1...While deleting char from string I'm getting follolwing Exception,

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 115

String string = "strings";
char[] arr = string.toCharArray();
StringBuilder builder=new StringBuilder();
for (int i=0; i<arr.length;i++)>if(arr[i]=='s'){
System.out.println(builder.deleteCharAt(arr[i]));
}

}
Posted

The string builder doesn't have anything in it, you don't initialize the string builder with the string you want. You need to do something like this:

StringBuilder builder = new StringBuilder(string);


Otherwise builder is an empty string, so when you try to delete out of it, there is nothing there and it throws an exception. Apologies if the above does not compile, I'm not a Java programmer.
   
String string ="strings";;
char[] arr = string.toCharArray();
StringBuilder builder=new StringBuilder(string);
for (int i=0,j=0; j<arr.length;i++,j++) {
if(arr[j]=='s'){
try{
//System.out.println(removeCharAt(string, i));
System.out.println(builder.deleteCharAt(i));
i--;
}
catch(StringIndexOutOfBoundsException siobe){
System.out.println("invalid input");
}


}

}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900