首页 > 解决方案 > 如何从另一个字符串中删除字符串?

问题描述

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

示例:“hello world,我的名字是 john”
删除:“ewo”
结果:“hllo rld 我的名字是 john”

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

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”,但这不是我需要的

标签: javastring

解决方案


尝试这个

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
}

推荐阅读