有一个简单的方法来删除子字符串从给定的字符串在Java?
例如:“Hello World!”,去掉“o”→“Hell Wrld!”
有一个简单的方法来删除子字符串从给定的字符串在Java?
例如:“Hello World!”,去掉“o”→“Hell Wrld!”
当前回答
如果你知道开始和结束索引,你可以使用它
string = string.substring(0, start_index) + string.substring(end_index, string.length());
其他回答
除了@DwB answer,你还可以使用StringUtils remove:
String hello = "hello world";
String hellYeah = StringUtils.remove(hello, "o");
或removeIgnoreCase:
String hello = "hellO world";
String hellYeah = StringUtils.remove(hello, "o");
replace('regex', 'replacement');
replaceAll('regex', 'replacement');
在你的例子中,
String hi = "Hello World!"
String no_o = hi.replaceAll("o", "");
你也可以使用Substring替换现有的字符串:
var str = "abc awwwa";
var Index = str.indexOf('awwwa');
str = str.substring(0, Index);
replaceAll(String regex, String replacement)
以上方法将帮助你得到答案。
String check = "Hello World";
check = check.replaceAll("o","");
你也可以使用番石榴的CharMatcher。removeFrom函数。
例子:
String s = CharMatcher.is('a').removeFrom("bazaar");