有一个简单的方法来删除子字符串从给定的字符串在Java?
例如:“Hello World!”,去掉“o”→“Hell Wrld!”
有一个简单的方法来删除子字符串从给定的字符串在Java?
例如:“Hello World!”,去掉“o”→“Hell Wrld!”
当前回答
你可以轻松地使用String.replace():
String helloWorld = "Hello World!";
String hellWrld = helloWorld.replace("o","");
其他回答
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()。
replace('regex', 'replacement');
replaceAll('regex', 'replacement');
在你的例子中,
String hi = "Hello World!"
String no_o = hi.replaceAll("o", "");
如果你知道开始和结束索引,你可以使用它
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");
你可以使用StringBuffer
StringBuffer text = new StringBuffer("Hello World");
text.replace( StartIndex ,EndIndex ,String);