Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

problem with code

  Asked By: Ronnie    Date: May 14    Category: Java    Views: 760
  

I am trying to create a swear word parser, i keep running
into a memory error..

public static String sanitize(String str)
{

String upper = str.toUpperCase();
int index=0;
for (int i=0; i<SWEAR.length; i++)
{
while((index = upper.indexOf(SWEAR[i].toUpperCase())) >=
0)
{
str = replace(str, index, SWEAR[i].length(),
CLEAN);

}
}
return str;
}

private static String replace(String str, int index, int len,
String curse)
{
StringBuffer buf = new StringBuffer(str.length());
buf.append(str.substring(0));
buf.append(curse);
buf.append(str.substring(index+len));
return buf.toString();
}

Share: 

 

3 Answers Found

 
Answer #1    Answered By: Fedde Bakker     Answered On: May 14

you have to do the replace on the upper string  as well or it will keep
finding the same swearword
the while condition uses the upper string for comparison

 
Answer #2    Answered By: Taylor White     Answered On: May 14

But also, your first "substring" statement is wrong.
As you have it - substring (0) - it simply returns the whole string, you need a
second parameter to define the length  of the substring. In your case, that'll
be "index" or "index - 1" I would think.

BTW If you want this code  to be efficient, you should look at the "replaceAll"
method which will do what you want much faster, I'd think. If it's just a
programming exercise, your approach is fine.

 
Answer #3    Answered By: Cay Nguyen     Answered On: May 14

I only knew because I wrote the code  for him in the first place, and it
was working when I sent it to him.
I didn't use replaceAll as it is case sensitive, whereas this (somewhat
clumsy) method is not..

 
Didn't find what you were looking for? Find more on problem with code Or get search suggestion and latest updates.




Tagged: