Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String replace?

Status
Not open for further replies.

shmmeee

Programmer
Apr 17, 2001
104
GB
Hi,
I'm new to java, I was wandering if there is a way to replace a substring within a string. e.g. say I've got a string : string1 = "Hello this is a string and it is pointless!" I could replace all the occurances of a word(say "is") with another word (eg. string1 becomes "Hello this WAS a string and it WAS pointless!") Is that possible or does anyone have any code that would do that?
TIA
 
There is a replace(char oldChar, char newChar) method in the String class but you can only change one char at a time - I am not sure if you can do it with more than one char at a time.
 
no, there isn't an existing method to do this for you. you'll have to do it yourself.
 
It's OK I decided I might as well spend half an hour coding it than 2 hours looking on the net for the answer :)
Thanks anyway
 
I was having a similar problem only...I was trying to replace a certain character (&&) with a HTML breakline. Is this even possible? I know you can do it in ASP, but I was wondering about Javascript
 
static String replace (String source, String toFind, String toInsert)
{
StringBuffer buf= new StringBuffer();
int cursor=0;
while ( true )
{
int foundAt=source.indexOf(toFind, cursor);
if ( foundAt >= 0)
{
buf.append( source.substring(cursor, foundAt) );
buf.append(toInsert);
}
else
{
buf.append(source.substring(cursor));
return buf.toString();
}
cursor=foundAt+1;
}
}
 
Almost...

The last line should be

cursor = foundAt + toFind.length();

which skips over the entire found substring.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top