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

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


当前回答

这对我很有用。

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

或者你可以用

String no_o = hi.replace("o", "");

其他回答

除了@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");
replaceAll(String regex, String replacement)

以上方法将帮助你得到答案。

String check = "Hello World";
check = check.replaceAll("o","");

查看Apache StringUtils:

static String replace(String text, String searchString, String replacement) Replaces all occurrences of a String within another String. static String replace(String text, String searchString, String replacement, int max) Replaces a String with another String inside a larger String, for the first max values of the search String. static String replaceChars(String str, char searchChar, char replaceChar) Replaces all occurrences of a character in a String with another. static String replaceChars(String str, String searchChars, String replaceChars) Replaces multiple characters in a String in one go. static String replaceEach(String text, String[] searchList, String[] replacementList) Replaces all occurrences of Strings within another String. static String replaceEachRepeatedly(String text, String[] searchList, String[] replacementList) Replaces all occurrences of Strings within another String. static String replaceOnce(String text, String searchString, String replacement) Replaces a String with another String inside a larger String, once. static String replacePattern(String source, String regex, String replacement) Replaces each substring of the source String that matches the given regular expression with the given replacement using the Pattern.DOTALL option.

这对我很有用。

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

或者你可以用

String no_o = hi.replace("o", "");
replace('regex', 'replacement');
replaceAll('regex', 'replacement');

在你的例子中,

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