Answers:
您可以轻松使用String.replace()
:
String helloWorld = "Hello World!";
String hellWrld = helloWorld.replace("o","");
static String replace(String text, String searchString, String replacement)
替换另一个String中所有出现的String。static String replace(String text, String searchString, String replacement, int max)
将字符串替换为较大字符串中的另一个字符串,以获取搜索字符串的第一个最大值。static String replaceChars(String str, char searchChar, char replaceChar)
将一个字符串中所有出现的字符替换为另一个。static String replaceChars(String str, String searchChars, String replaceChars)
一次性替换字符串中的多个字符。static String replaceEach(String text, String[] searchList, String[] replacementList)
替换另一个String中所有出现的String。static String replaceEachRepeatedly(String text, String[] searchList, String[] replacementList)
替换另一个String中所有出现的String。static String replaceOnce(String text, String searchString, String replacement)
一次用较大的字符串中的另一个字符串替换一个字符串。static String replacePattern(String source, String regex, String replacement)
使用Pattern.DOTALL选项,用给定的替换项替换与给定的正则表达式匹配的源字符串的每个子字符串。
replace('regex', 'replacement');
replaceAll('regex', 'replacement');
在您的示例中
String hi = "Hello World!"
String no_o = hi.replaceAll("o", "");
这是从给定字符串中删除所有子字符串的实现
public static String deleteAll(String str, String pattern)
{
for(int index = isSubstring(str, pattern); index != -1; index = isSubstring(str, pattern))
str = deleteSubstring(str, pattern, index);
return str;
}
public static String deleteSubstring(String str, String pattern, int index)
{
int start_index = index;
int end_index = start_index + pattern.length() - 1;
int dest_index = 0;
char[] result = new char[str.length()];
for(int i = 0; i< str.length() - 1; i++)
if(i < start_index || i > end_index)
result[dest_index++] = str.charAt(i);
return new String(result, 0, dest_index + 1);
}
isSubstring()方法的实现在这里