This example will replace an occurrences of an old char with a new char within a given string using java and apache commons. There is multiple overloaded methods of String.replace
so be sure to check the javadocs. The snippets below are random tweets from twitter where a String will be replaced by another String.
Straight up Java @Test
public void replace_string_java () {
String randomTweet = "I didn't realize that texting through "
+ "@GoogleVoice worked while riding on a "
+ "jet plane #forgottoblockport" ;
String modifiedPhrase = randomTweet . replace ( "@GoogleVoice" , "@GVoice" );
assertEquals ( "I didn't realize that texting through @GVoice "
+ "worked while riding on a jet plane #forgottoblockport" ,
modifiedPhrase );
}
Apache Commons @Test
public void replace_string_apache () {
String randomTweet = "Millennials are much more likely to share "
+ "personal data with retailers in "
+ "order to get customized offers" ;
String modifiedPhrase = StringUtils . replace ( randomTweet , "personal" ,
"privae" );
assertEquals ( "Millennials are much more likely to share privae "
+ "data with retailers in order to get customized offers" ,
modifiedPhrase );
}
Replace char within a string posted by Justin Musgrove on 09 November 2014
Tagged: java and java-string
Share on: Facebook Google+
All the code on this page is available on github:
ReplaceStringInString.java