如何使用replace(char,char)来替换所有字符b的实例 [英] How to use replace(char, char) to replace all instances of character b with nothing
问题描述
我如何使用替换(char,char)以替换所有字符b的实例。
How do i use replace(char, char) to replace all instances of character "b" with nothing.
例如:
Hambbburger to Hamurger
编辑:有一个约束,我可能只使用1.4.2,这意味着没有重载的重载版本!
There is a constraint, i may only use 1.4.2, meaning no overloaded version of replace!
推荐答案
还有一个 replaceAll 使用字符串的函数,但请注意它将它们作为正则表达式进行删除,但是替换单个字符将会很好。
There's also a replaceAll function that uses strings, note however that it evals them as regexes, but for replacing a single char will do just fine.
以下是一个例子:
String meal = "Hambbburger";
String replaced = meal.replaceAll("b","");
请注意,已替换
变量是必要的 replaceAll
不会更改字符串,但会创建一个带有替换的新字符串( String
在java中是不可变的) 。
Note that the replaced
variable is necessary since replaceAll
doesn't change the string in place but creates a new one with the replacement (String
is immutable in java).
如果要替换的字符在正则表达式中具有不同的含义(例如。
char将匹配任何字符,而不是点)你需要引用
这样的第一个参数:
If the character you want to replace has a different meaning in a regex (e.g. the .
char will match any char, not a dot) you'll need to quote
the first parameter like this:
String meal = "Ham.bur.ger";
String replaced = meal.replaceAll(Pattern.quote("."),"");
这篇关于如何使用replace(char,char)来替换所有字符b的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!