扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

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

扬州沐宇科技
2024-01-19 11:21:55
stringbuffer

要删除字符串中的指定字符串,可以使用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循环来多次删除指定字符串,直到字符串中不再包含该指定字符串为止。

扫码添加客服微信