如何从给定的字符串中删除子字符串?


190

有没有一种简便的方法可以从StringJava中的给定字符串中删除子字符串?

示例:"Hello World!",删除"o""Hell Wrld!"

Answers:



9

您可以使用StringBuffer

StringBuffer text = new StringBuffer("Hello World");
text.replace( StartIndex ,EndIndex ,String);

8

查看Apache StringUtils

  • 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选项,用给定的替换项替换与给定的正则表达式匹配的源字符串的每个子字符串。

1
刚刚对replacePattern进行了基准测试,它比运行自定义Java代码慢6倍。
Alex Arvanitidis


4

这对我有用。

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

或者你可以使用

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



1
replaceAll(String regex, String replacement)

以上方法将有助于获得答案。

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

1

您还可以使用Substring替换现有的字符串:

var str = "abc awwwa";
var Index = str.indexOf('awwwa');
str = str.substring(0, Index);

0

这是从给定字符串中删除所有子字符串的实现

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()方法的实现在这里


0
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()


0

如果您知道开始和结束索引,则可以使用此索引

string = string.substring(0, start_index) + string.substring(end_index, string.length());
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.