gpt4 book ai didi

java - 如何从另一个字符串中删除字符串?

转载 作者:行者123 更新时间:2023-12-01 07:46:11 26 4
gpt4 key购买 nike

我想从另一个字符串中删除一个字符串,而不是所有字母。

示例:“ Hello World ,我的名字是约翰”
删除:“ewo”
结果:“你好,我叫约翰”

我的程序删除了所有要删除的字母

String text = "hello world my name is john";
int num = 1;

for (int i = 0; i < num; i++) {
String del = ewo;

String[] delArray = del.split("");

for (int j = 0; j < delArray.length; j++) {

text = text.replace(delArray[j], "");
}
System.out.println(text);
}

我的程序返回:“hll rld my nam is jhn”,但这不是我需要的

最佳答案

试试这个

String text = "hello world my name is john";
int num = 1;

for (int i = 0; i < num; i++) {
String del = ewo;

String[] delArray = del.split("");

for (int j = 0; j < delArray.length; j++) {

text = text.replaceFirst(delArray[j], "");
}
System.out.println(text); //output => hll orld my name is john
}

关于java - 如何从另一个字符串中删除字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51685001/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com