• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

String replace function

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Does anyone have a function that will replace stings within a string with new values.
e.g. public String(String theString, String replace, String replaceWith)
This function would replace all occurances of "replace" with "replaceWith" in the original "theString". it would then return this new string
Thanks
 
Sheriff
Posts: 9109
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Check out the Str class here which has lots of useful methods. Otherwise you could use the replace method in the StringBuffer class.
 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
replace method isuse to replace a character replace(char,char)
for example:
String cat="Sweet Sister";
String m = cat.replace('e','x');
System.out.println(m);
Out put:
Swxxt Sistxr
it will replace the e with x
hope its clear
 
Ranch Hand
Posts: 123
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public static String replace(String s, String repl, String with)
{
if (repl == null)
return s;
if (with == null)
with = "";
int offset = 0;
int p = s.indexOf(repl);
while (p >= 0)
{
s = s.substring(0,p) + with + s.substring(p + repl.length());
offset = p + with.length();
p = s.indexOf(repl,offset);
}
return s;
}
 
Oh sure, it's a tiny ad, but under the right circumstances, it gets bigger.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic