1

我需要一些帮助来找到一个单词的长度以及有多少单词有这个长度。例如,如果句子是"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();
        }
}

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

4

2 回答 2

1

你对我的付出没有任何意义。我的事情会为你工作。

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
于 2013-10-23T05:06:59.720 回答
0

它实际上很容易使用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]);
 }
于 2013-10-23T05:02:58.253 回答