我需要一些帮助才能找到一个单词的长度以及有多少单词具有该长度。例如,如果句子是"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();
}
}
其中只给出了每个单词的长度。
答案 0 :(得分: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());
}
Out put
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
答案 1 :(得分: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]);
}