【问题标题】:How to check for equal words in string array in JAVA如何在JAVA中检查字符串数组中的相等单词
【发布时间】:2012-09-11 20:56:42
【问题描述】:

这应该很简单(我认为),但我就是无法正确...:|

任务如下:

询问用户一些输入。输入必须拆分为单个单词并放入数组中。所有单词都应该被计算在内。如果存在相同的单词,它们会在输出中得到“+1”。 最后,我想打印出列表中正确数量的计数单词。我的前两列是正确的,但是相同单词的单词计数器让我很头疼。如果一个词被发现是相等的,它就不能在生成的列表中出现两次! :!

我是一个完整的 JAVA 新手,所以请善待代码判断。 ;)

到目前为止,这是我的代码:

package MyProjects;

import javax.swing.JOptionPane;

public class MyWordCount {
public static void main(String[] args) {

    //User input dialog
    String inPut = JOptionPane.showInputDialog("Write som text here");

    //Puts it into an array, and split it with " ".
    String[] wordList = inPut.split(" ");

    //Print to screen
    System.out.println("Place:\tWord:\tCount: ");

    //Check & init wordCount
    int wordCount = 0;

    for (int i = 0; i < wordList.length; i++) {

        for (int j = 0; j < wordList.length; j++){

            //some code here to compare
            //something.compareTo(wordList) ?

        }

        System.out.println(i + "\t" + wordList[i]+ "\t" + wordCount[?] );
    }

}
}

【问题讨论】:

  • 也许我应该用一个 for-each 循环来改变两个 for-loop?
  • 使用List&lt;String&gt; words = Arrays.asList(inPut.split(" "));,然后使用Collections.frequency(words, word) 确定单词的实例数。
  • 这个问题的回答还没有让您满意吗?您需要更多信息吗?
  • 一切都好! :) 感谢所有提示!
  • @Mechanicalsnail 感谢您的提醒。虽然我认为我的评论是在此更改之前发表的,但很高兴知道未来。

标签: java arrays string sorting


【解决方案1】:

您可以使用 Hashmap 来做到这一点。 Hashmap 存储键值对,每个键必须是唯一的。

因此,在您的情况下,键将是您拆分的字符串的一个单词,而值将是它的计数。

将输入拆分为单词并将它们放入字符串数组后,将第一个单词作为键放入 Hashmap,并将 1 作为它的值。对于每个后续单词,您可以使用函数 containsKey() 将该单词与 Hashmap 中的任何现有键匹配。如果返回 true,则将该键的值(计数)加 1,否则将单词和 1 作为新的键值对放入 Hashmap。

【讨论】:

    【解决方案2】:

    所以为了比较两个字符串,你可以这样做:

    String stringOne = "Hello";
    String stringTwo = "World";
    stringOne.compareTo(stringTwo);
    //Or you can do
    stringTwo.compareTo(stringOne); 
    

    您不能像评论中那样将字符串与字符串数组进行比较。你必须在这个字符串数组中取一个元素,然后比较它(所以 stringArray[elementNumber])。

    为了计算有多少单词,如果您要确定重复单词的数量,您会想要一个整数数组(所以创建一个新的 int[])。新 int[] 中的每个位置都应对应于单词数组中的单词。这将允许您计算单词重复的次数。

    【讨论】:

      【解决方案3】:
      import java.util.ArrayList;
      import java.util.regex.PatternSyntaxException;
      
      import javax.swing.JOptionPane;
      
      public class Main {
      
      /**
       * @param args
       */
      public static void main(String[] args) {
      
          //Print to screen
          System.out.println("Place:\tWord:\tCount: ");
      
          //User input dialog
          String inPut = JOptionPane.showInputDialog("Write som text here");
      
          //Puts it into an array, and split it with " ".
          String[] wordList;
          try{
              wordList = inPut.split(" ");
          }catch(PatternSyntaxException e) {
              // catch the buggy!
              System.out.println("Ooops.. "+e.getMessage());
              return;
          }catch(NullPointerException n) {
              System.out.println("cancelled! exitting..");
              return;
          }
      
          ArrayList<String> allWords = new ArrayList<String>();
          for(String word : wordList) {
              allWords.add(word);
          }
      
          // reset unique words counter
          int uniqueWordCount = 0;
      
          // Remove all of the words
          while(allWords.size() > 0) {
              // reset the word counter
              int count = 0;
      
              // get the next word
              String activeWord = allWords.get(0);
      
              // Remove all instances of this word
              while(doesContainThisWord(allWords, activeWord)) {
                  allWords.remove(activeWord);
                  count++;
              }
      
              // increase the unique word count;
              uniqueWordCount++;
      
              // print result.
              System.out.println(uniqueWordCount + "\t" + activeWord + "\t" + count );
      
          }
      
      }
      
      /**
       * This function returns true if the parameters are not null and the array contains an equal string to newWord.
       */
      public static boolean doesContainThisWord(ArrayList<String> wordList, String newWord) {
          // Just checking...
          if (wordList == null || newWord == null) {
              return false;
          }
      
          // Loop through the list of words
          for (String oldWord : wordList) {
              if (oldWord.equals(newWord)) {
                  // gotcha!
                  return true;
              }
          }
          return false;
      }
      
      }
      

      【讨论】:

        【解决方案4】:

        这是一个使用 WordInfo 对象映射的解决方案,它记录文本中单词的位置并将其用作计数。 LinkedHashMap 保留键从首次输入时开始的顺序,因此只需遍历键即可为您提供“按出现顺序转换”

        您可以使这种大小写不敏感,同时保留第一次出现的大小写,方法是将所有键存储为小写,但将原始大小写存储在 WordInfo 对象中。或者只是将所有单词转换为小写并保留它。 您可能还想考虑在拆分之前从第一个文本中删除所有 , / . / " 等,但无论如何你永远无法做到完美。

        import java.util.LinkedHashMap;
        import java.util.Map;
        
        import javax.swing.JOptionPane;
        
        public class MyWordCount {
            public static void main(String[] args) {
        
                //User input dialog
                String inPut = JOptionPane.showInputDialog("Write som text here");
        
                Map<String,WordInfo> wordMap = new LinkedHashMap<String,WordInfo>();
        
                //Puts it into an array, and split it with " ".
                String[] wordList = inPut.split(" ");
        
                for (int i = 0; i < wordList.length; i++) {
                    String word = wordList[i];
                    WordInfo wi = wordMap.get(word);
                    if (wi == null) {
                        wi = new WordInfo();            
                    }
                    wi.addPlace(i+1);
                    wordMap.put(word,wi);           
                }
        
                //Print to screen
        
                System.out.println("Place:\tWord:\tCount: ");
        
                for (String word : wordMap.keySet()) {          
        
                    WordInfo wi = wordMap.get(word);        
                    System.out.println(wi.places() + "\t" + word + "\t" + wi.count());
                }
        
              }
        }
        

        还有 WordInfo 类:

        import java.util.ArrayList;
        import java.util.List;
        
        public class WordInfo {
        
            private List<Integer> places;
        
            public WordInfo() {
                this.places = new ArrayList<>();
            }
        
            public void addPlace(int place) {
                this.places.add(place);
            }
        
        
            public int count() {
                return this.places.size();
            }
        
            public String places() {
                if (places.size() == 0)
                    return "";
        
                String result = "";
                for (Integer place : this.places) {
                    result += ", " + place;
                }
                result = result.substring(2, result.length());
                return result;
            }
        }
        

        【讨论】:

          【解决方案5】:

          感谢您尝试帮助我。 -这就是我最终做的:

          import java.util.ArrayList;
          
          import javax.swing.JOptionPane;
          
          public class MyWordCount {
          public static void main(String[] args) {
          
              // Text in
              String inText = JOptionPane.showInputDialog("Write some text here");
          
              // Puts it into an array, and splits
              String[] wordlist = inText.split(" ");
          
              // Text out (Header)
              System.out.println("Place:\tWord:\tNo. of Words: ");
          
              // declare Arraylist for words
              ArrayList<String> wordEncounter = new ArrayList<String>();
              ArrayList<Integer> numberEncounter = new ArrayList<Integer>();
          
              // Checks number of encounters of words
              for (int i = 0; i < wordlist.length; i++) {
                  String word = wordlist[i];
          
                  // Make everything lowercase just for ease...
                  word = word.toLowerCase();
          
                  if (wordEncounter.contains(word)) {
                      // Checks word encounter - return index of word
                      int position = wordEncounter.indexOf(word);
                      Integer number = numberEncounter.get(position);
                      int number_int = number.intValue();
                      number_int++;
                      number = new Integer(number_int);
                      numberEncounter.set(position, number);
          
                      // Number of encounters - add 1;
                  } else {
                      wordEncounter.add(word);
                      numberEncounter.add(new Integer(1));
                  }
          
              }
          
              // Text out (the list of words)
              for (int i = 0; i < wordEncounter.size(); i++) {
                  System.out.println(i + "\t" + wordEncounter.get(i) + "\t"
                          + numberEncounter.get(i));
              }
          
            }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多