I need to find a similar slick way in java to do multi string replace the same way you can do this in php with str_replace.
I want to take a string and then returns a string with the numbers 1 to 10 replaced with the word for those numbers.
"I won 7 of the 10 games and received 30 dollars." => "I won seven of the ten games and received 30 dollars."
In php, you can do:
function replaceNumbersWithWords($phrase) {
$numbers = array("1", "2", "3","4","5","6","7","8","9","10");
$words = array("one", "two", "three","four","five","six","seven","eight","nine","ten");
return str_replace($numbers,$words,$phrase);
}
I'm not sure there is an elegant way to do regular expressions on this particular case with String.replace(), and I don't want to use what I feel is a brute force approach to do this: like here: How to replace multiple words in a single string in Java?.
You can do that with replaceEach() from StringUtils:
http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#replaceEach(java.lang.String, java.lang.String[], java.lang.String[])
StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With