温馨提示×

怎么使用stringbuffer删除指定字符串

小亿
142
2024-01-19 11:21:55
栏目: 编程语言

要删除字符串中的指定字符串,可以使用StringBuffer的replace方法。下面是一个示例:

StringBuffer sb = new StringBuffer("Hello World");
String strToRemove = "World";

int index = sb.indexOf(strToRemove);
while (index != -1) {
    sb.replace(index, index + strToRemove.length(), "");
    index = sb.indexOf(strToRemove, index);
}

System.out.println(sb.toString());

以上代码将会输出"Hello ",即将指定的字符串"World"删除。这里使用了while循环来多次删除指定字符串,直到字符串中不再包含该指定字符串为止。

0