有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

查找字符串中单词的长度,并查找有多少单词具有该长度。(爪哇)

我需要一些帮助来找出一个单词的长度以及有多少个单词有这个长度。例如,如果句子是"I am going to find some string lengths"

输出将是

Number of String with length 1 is 1

Number of String with length 2 is 2

Number of String with length 4 is 2

Number of String with length 5 is 1

Number of String with length 6 is 1

Number of String with length 7 is 1

到目前为止,我得到了这个:

    String word;
    int wordlength;
    int count = 0;

    Scanner inFile = 
            new Scanner(new FileReader("C:\\Users\\Matt\\Documents\\WordSize.txt\\"));

    PrintWriter outFile = 
            new PrintWriter("wordsizes.out");

    while (inFile.hasNext())
    {
        word = inFile.next();

        wordlength = word.length();

        if (count >= 0)
            outFile.println(wordlength);

        count++;
    }

    outFile.close();
        }
}

这只是给出了每个单词的长度


共 (2) 个答案

  1. # 1 楼答案

    使用string.split()函数实际上很容易。我写信是为了演示一种解决方案:

    String inputStr = "I am going to find some string lengths";
    String str[] = inputStr.split(" "); // split the strings: "I", "am", "going", etc
    
    int maxSize = 0;
    
    for(String s: str)   // finding the word with maximum size and take its length
      if(maxSize < s.length())
            maxSize = s.length();
    
    int lCount[] = new int[maxSize+1]; 
    
    
    for(String s1: str)
    {
       lCount[s1.length()]++; // count each length's occurance
    }
    
     for(int j=0; j<lCount.length;j++)
     {
         System.out.println("String length: "+j+" count: "+lCount[j]);
     }
    
  2. # 2 楼答案

    你对我说的话毫无意义。我相信下面的东西对你有用

    String str="I am going to find some string lengths";
      String[] arr=str.split(" ");
        Map<Integer,Integer> lengthMap=new HashMap<>();
        for(String i:arr){
            Integer val=lengthMap.get(i.length());
            if(val==null){
               val=0;
            }
            lengthMap.put(i.length(),val+1);
        }
        for(Map.Entry<Integer,Integer> i:lengthMap.entrySet()){
            System.out.println("Number of String with length "+i.getKey()+" is "+i.getValue());
        }
    

    发出

      Number of String with length 1 is 1
      Number of String with length 2 is 2
      Number of String with length 4 is 2
      Number of String with length 5 is 1
      Number of String with length 6 is 1
      Number of String with length 7 is 1