有一个简单的方法来删除子字符串从给定的字符串在Java?

例如:“Hello World!”,去掉“o”→“Hell Wrld!”


当前回答

replace('regex', 'replacement');
replaceAll('regex', 'replacement');

在你的例子中,

String hi = "Hello World!"
String no_o = hi.replaceAll("o", "");

其他回答

你也可以使用番石榴的CharMatcher。removeFrom函数。

例子:

 String s = CharMatcher.is('a').removeFrom("bazaar");
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);
private static void replaceChar() {
    String str = "hello world";
    final String[] res = Arrays.stream(str.split(""))
            .filter(s -> !s.equalsIgnoreCase("o"))
            .toArray(String[]::new);
    System.out.println(String.join("", res));
}

如果你有一些复杂的逻辑来过滤字符,那就用另一种方法代替replace()。

你应该看看StringBuilder/StringBuffer,它允许你删除,插入,替换指定偏移量的字符。