【问题标题】:Comparing LinkedList Elements to String in Java将 LinkedList 元素与 Java 中的字符串进行比较
【发布时间】:2020-07-20 02:43:49
【问题描述】:

我正在尝试编写一个程序,将 LinkedList 中的字符串与单个字符串进行比较。我正在尝试检查 LinkedList 中的字符串是否正好有一些数字:int n 单个字符串中的相同字母。

例如,如果 LinkedList 中的第一个单词是"word",n = 2,并且单个字符串是"weed"。这些单词包含 2 个相同的字母。未遵循此规则的所有其他元素将从 LinkedList 中删除。这些单词的大小也是一样的。

我已经编写了下面的代码,但我担心这不是实现它的最佳方式,否则while循环将无限继续。

    int count = 0;              
    for (String word : list) {
            for (int i = 0; i < str.length(); i++){
                    while (count != n) {
                           if (word.contains("" + str.charAt(i))){
                                count ++;
                            }
                            if (count != n) {
                                list.remove(word);
                            }
                        }
                    }
             }

【问题讨论】:

    标签: java string while-loop linked-list


    【解决方案1】:

    您根本不需要 while 循环来解决这个问题。这段代码应该可以工作。

    for (String word : list)
    {
       int count = 0; 
       for (int i = 0; i < str.length(); i++)
       {
            if (word.contains("" + str.charAt(i)))
            {
               count ++;
            }
        }
        if (count != n)
        {
            list.remove(word);
        }
    
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-08
      • 2017-02-20
      • 2010-10-06
      • 2012-08-31
      相关资源
      最近更新 更多