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 Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

more specific replace method

Status
Not open for further replies.

A5k

Programmer
Jul 29, 2001
54
CA
Hi all,
I'm looking for a method like str.replace(char,char) but instead replaces only one instance of the value.

ie: String str = "java";
str = str.replace('a','x');
output > jxvx

What i'm looking for:
String str = "java";
str = str.SomeMethod('a','x');
output > jxva

Does anyone know if this exists without using StringBuffer???

-a5k
 
an off the top of my head solution. access the String as a char array. find the first index of the character you're looking for, and set the character at that position in the char array to the string you want. I'm not completely sure, but I think that works. Liam Morley
lmorley@gdc.wpi.edu
"light the deep, and bring silence to the world.
light the world, and bring depth to the silence."
 
Try this little method:

public static String replace( String str, String oldStr, String newStr )
{
int index = str.indexOf( oldStr );
String result = str.substring( 0, index ) + newStr + str.substring( index + 1, str.length() );

return( result );
}

That should do what you are looking for.

-gc "I don't look busy because I did it right the first time."
 
I'm pretty sure that would create new strings in memory, which is why A5k mentioned StringBuffer. Liam Morley
lmorley@gdc.wpi.edu
"light the deep, and bring silence to the world.
light the world, and bring depth to the silence."
 
thanks all,
imotic, I tried that idea before posting with this type of code:
Code:
  for(int i=0;i<str.length();i++)
    charArray[i] = str.charAt(i);
But javac didn't like that idea at all. It didn't allow me to have a char within a string to be a single char?!?! Any ideas of why?

godcomplex, thanks for the code, I figured I probably had to write my own method ;)

thanks again,
-a5k
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top