【问题标题】:How to loop through string and remove specific elements?如何遍历字符串并删除特定元素?
【发布时间】:2015-05-29 14:23:30
【问题描述】:

所以如果我有这个:'我的消息需要检查'。

我有一个字符串:[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'.

【问题讨论】:

    标签: java arrays filtering


    【解决方案1】:

    你可以试试:

    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
    }
    

    【讨论】:

    • 仍然,您会得到1 作为第一个数字,而在拆分消息后,“my”将位于 0 索引处。您必须将所有数值减 1。我在您的代码中没有看到。
    【解决方案2】:

    向后循环并用空格替换索引,然后构造一个没有空格的新字符串。

        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());
    

    【讨论】:

      【解决方案3】:

      首先你需要从filter获取索引作为整数,然后删除句子中这个位置的单词。

          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());
      

      输出:

      消息检查

      【讨论】:

        【解决方案4】:

        我建议您创建第二个字符串(或列表)作为结果。

        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.
           }
        }
        

        【讨论】:

          【解决方案5】:

          在要删除的项目数组上向后循环

          String[] toFilter = filter.split("-");
          for ( int i = toFilter.length() - 1; i >= 0; i-- ){
              ///remove the items
          }
          

          【讨论】:

            猜你喜欢
            • 2021-10-02
            • 2012-01-13
            • 1970-01-01
            • 2019-10-16
            • 2018-08-22
            • 2019-03-28
            • 2016-01-09
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多