所以如果我有这个:'我的消息需要检查'。
我有一个字符串:[1][3][4]
。这些是我要删除的邮件的元素(例如,'我的'将是元素1,'将是元素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'.
答案 0 :(得分:1)
向后循环移除项目数组
String[] toFilter = filter.split("-");
for ( int i = toFilter.length() - 1; i >= 0; i-- ){
///remove the items
}
答案 1 :(得分:1)
首先,您需要将{{1>}中的索引作为整数,然后删除句子中此位置的单词。
filter
输出:
消息检查
答案 2 :(得分:0)
我建议您创建第二个字符串(或List)作为结果。
String messageToFilter = "my message that needs checking";
String filter = "[1]-[3]-[4]";
String result = null;
for (String curElement : filter.split("-")) {
if(curElement.equalsIgnoreCase("[3]")) {
result = curElement;
break; // or whatever you need to do with the result.
}
}
答案 3 :(得分:0)
你可以尝试:
public static void main(String[] argss){
String messageToFilter = "my message that needs checking";
String filter = "[1]-[3]-[4]";
ArrayList<Integer> lst=new ArrayList<Integer>();
String[] fltr = filter.split("-");
for (String curElement : fltr) {
// populate lst with indexes to filter !
lst.add(Character.getNumericValue(curElement.charAt(1)));
}
String result="";
String[] msgSplitted=messageToFilter.split(" ");
for(int i=0; i<msgSplitted.length;i++){
if(!lst.contains(i+1))
{
//Checks if this index i must be flitered
//Otherwise, add matching word to result
result=result+" "+msgSplitted[i];
}
}
System.out.print(result); //your result
}
答案 4 :(得分:0)
向后循环并用空格替换索引,然后构造一个没有空格的新String。
String filterString = "[1]-[3]-[4]";
String messageToFilter = "my message that needs checking";
String[] words = messageToFilter.split("\\s");// filterString for white space
String[] indexes = StringUtils.split(filterString, "]|\\[|-");// filterString the numbers out
for (int i = words.length - 1; i >= 0; i--) {
for (int j = indexes.length - 1; j >= 0; j--) {
if (i > j)
break;
if (i == j) {
int valueAtIndex = Integer.parseInt(indexes[i]);
words[valueAtIndex-1] = "";
break;
}
}
}
StringBuffer bf = new StringBuffer();
for (String word : words) {
if(word!="")
bf.append(word).append(" ");
}
System.out.println(bf.toString());