Sunday, 8 September 2013

I am trying to remove characters in a string from a defined string. the error comes here: if(s.charAt(x) == punct.charAt(y))

I am trying to remove characters in a string from a defined string. the
error comes here: if(s.charAt(x) == punct.charAt(y))

String dirtyStr = "Who. do yo$u th,ink you are?!";
System.out.println(scrub(dirtyStr));
static String punct = ".,?!:;\"(){}{}<>";
public static String scrub(String s)
{
for(int x = 0; x < s.length(); x++)
{
for(int y = 0; y < punct.length(); y++)
{
if(s.charAt(x) == punct.charAt(y))
{
s = s.replace("" + s.charAt(x), "");
}
}
}
return s;
}
Stack trace
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 28
at java.lang.String.charAt(String.java:658)
at StringMethods_7_Gupta.scrub(StringMethods_7_Gupta.java:120)
at StringMethods_7_Gupta.main(StringMethods_7_Gupta.java:95)

No comments:

Post a Comment