如何从字符串Java中删除多个单词

问题描述 投票:0回答:2

我是java新手,目前我正在学习字符串。

如何从字符串中删除多个单词?

我很高兴收到任何提示。

class WordDeleterTest {
    public static void main(String[] args) {
        WordDeleter wordDeleter = new WordDeleter();

        // Hello
        System.out.println(wordDeleter.remove("Hello Java", new String[] { "Java" }));

        // The Athens in
        System.out.println(wordDeleter.remove("The Athens is in Greece", new String[] { "is", "Greece" }));
    }
}

class WordDeleter {
    public String remove(String phrase, String[] words) {
        String[] array = phrase.split(" ");
        String word = "";
        String result = "";

        for (int i = 0; i < words.length; i++) {
            word += words[i];
        }
        for (String newWords : array) {
            if (!newWords.equals(word)) {
                result += newWords + " ";
            }
        }
        return result.trim();
    }
}

输出:

Hello
The Athens is in Greece

我已经尝试过在这里使用replace,但没有成功。

java string replaceall
2个回答
4
投票

您可以使用流来完成:

String phrase = ...;
List<String> wordsToRemove = ...;
        
String result = Arrays.stream(phrase.split("\s+"))
     .filter(w -> !wordsToRemove.contains(w))
     .collect(Collectors.joining(" "));   

3
投票

程序员经常这样做:

String sentence = "Hello Java World!";
sentence.replace("Java", "");
System.out.println(sentence);

=> 你好 Java 世界

字符串是不可变的,replace函数返回一个新的字符串对象。所以改为写

String sentence = "Hello Java World!";
sentence = sentence.replace("Java", "");
System.out.println(sentence);

=> 世界你好!

(空白仍然存在)

有了这个,你的替换函数可能看起来像这样

public String remove(String phrase, String[] words) {
    String result = phrase;
    for (String word: words) {
        result = result.replace(word, "").replace("  ", " ");
    }
    return result.trim();
}

现在,此解决方案将删除短语中出现的所有单词 - 无论它是单词还是单词的一部分。正如OP评论的那样,从“This is Sparta”中删除“is”将导致“Th Sparta”。为了解决这个问题,请确保要替换的单词嵌入在空白字符之间。这是切换到正则表达式的完美情况。

public String remove(String phrase, String[] words) {
    String result = phrase;
    for (String word: words) {
        String regexp = "\\s" + word + "\\s";
        result = result.replaceAll(regexp, " ");
    }
    return result.trim();
}

解释:

模式序列

\s
类似于空白(空格、制表符、换行符……)。双反斜杠对于 Java 编译器来说是必要的,以免将单个反斜杠解释为其他字符的转义字符。因此,正则表达式匹配单词前后的空格,并指示replaceAll将该匹配替换为单个空格。这也意味着现在不需要第二次调用删除双空格。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.