gpt4 book ai didi

java - 查找字符串中某个单词的长度,并查找有多少个单词具有该长度。 ( java )

转载 作者:太空宇宙 更新时间:2023-11-04 07:19:25 24 4
gpt4 key购买 nike

我需要一些帮助来确定单词的长度以及有多少单词具有该长度。例如,如果句子是“我要找到一些字符串长度”

输出为

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();
}
}

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

最佳答案

你的输出对我来说没有任何意义。我接下来的事情对你有用。

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

关于java - 查找字符串中某个单词的长度,并查找有多少个单词具有该长度。 ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19533003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com