gpt4 book ai didi

java - 如何循环遍历字符串并删除特定元素?

转载 作者:行者123 更新时间:2023-12-02 04:50:40 26 4
gpt4 key购买 nike

所以,如果我有这样的内容:“我的消息需要检查”。

我有一个字符串:[1][3][4]。这些是我想要删除的消息元素(例如“my”将是元素 1,“that”将是元素 3)。

我如何循环遍历此消息并删除另一个字符串中的元素?

示例:

String messageToFilter = "my message that needs checking";
String filter = "[1]-[3]-[4]";

for (String curElement : filter.split("-")) {
//If I remove element [0], element [3] is then moved to [2]; so not sure what to do!
}

//So at this stage I need the messageToFilter, but with the elements from filter removed.
//In the example above this would output 'message checking'.

最佳答案

首先,您需要从过滤器中获取整数索引,然后删除句子中该位置的单词。

    String messageToFilter = "my message that needs checking";
// Split into an array of words
String[] words = messageToFilter.split("\\s+");

// get the indexes
Pattern pat = Pattern.compile("(\\d+)");
Matcher mat = pat.matcher("[1]-[3]-[4]");
while (mat.find()) {
int index = Integer.parseInt(mat.group());
// set the matching word to null (assuming the indexes start at 1)
words[index-1] = null;
}
// Rebuild the message
StringBuilder messageFiltered = new StringBuilder();
for (String w : words) {
if (w != null) {
messageFiltered.append(w).append(" ");
}
}
System.out.println(messageFiltered.toString());

输出:

message checking

关于java - 如何循环遍历字符串并删除特定元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29263726/

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