I need some help with finding text in a string and replacing it?

I’m working on a program that needs to be able to search a string of text for certain words and then replace them with something else. I believe the best way (I’m probably wrong though :)) would be to compare the string to an ArrayList of words, and then replace the words with different ones. Does this sound like it would work? If it does how do I compare individual words inside the string to the words in the arrayList? Thanks.

I’ve got another quick question. When using the replace() method, how come I can’t just do

object.text.replace("abc", "def");
System.out.println(object.text);

Whenever I do that it just gives me the same string that was stored in object.text. But when I do

object.text = object.text.replace("abc", "def");
System.out.println(object.text);

it works fine. Is that because the replace() method returns a string? Thanks.

It creates a new String.

String str = object.text.replace("abc", "def");
System.out.prinlnt(str);

first for better efficiency you may use http://java.sun.com/j2se/1.4.2/docs/api/java/lang/StringBuffer.html

may be you can use something like that ?


class MyString
{
 public String value;
 
 public MyString(String value)
 {
 	this.value=value;
 }
 
 String replace(String a,String b)
 {
  this.value=this.value.replace(a,b);
  return this.value;
 }

 public String toString()
 {
  return this.value;
 }
}

class myObj
{
 MyString text;
 myObj(String value)
 {
  this.text=new MyString(value);
 }
}

myObj object=new myObj("abc");
object.text.replace("abc", "def");
System.out.println(object.text);

you cannot overide String as it is a final class but providing a toString method in a class will make you able to use it as a string :

this works:


System.out.println("a real String" + object.text);

this works too:


MyString s=new MyString("a fake string");
String b= "a real string " + s;
System.out.println(b);

If you want to go through a dictionary-like array and then replace all the words in the string with those in the dictionary you might want to do something like this:


for(int x=0;x<dictionary.lenght;x++){
  obj.text = obj.text.replace(dictionary[x][0], dictionary[x][1]);
}

where 0 and 1 is just the word to find and what to replace it with respectively.

If you want to compare the words in the string to an array then in pre-1.5 JDK you could use StringTokenizer and from 1.5 you can use string.split(" ") to get an array containing all the words from your string. But don’t use this if you only want to replace words, because then you’ll have to reconstruct the string from the array.

PS: Download or check out the JDK docs then you can check out all the String manipulation methods.

Wow, thanks a lot, it makes much more sense now! ;D One more question. I was planning on using this as a basic chat filter for a game. Is this the most efficient way to do it or are there better ones? Thanks.