gpt4 book ai didi

JAVA:计算字符串上的每个单词,并计算单词上的每个字母

转载 作者:行者123 更新时间:2023-11-30 07:10:15 25 4
gpt4 key购买 nike

所以,我有一个 java 作业,其中有一个带有短语的字符串。我需要计算短语中的每个单词,然后计算每个单词有多少个字母。我已经能够使用 Tokenizer 将短语拆分为单词,然后使用 .countTokens() 计算并打印单词的数量。但是,我无法计算每个单词中的字母。

基本上输出应该是这样的:

"Nihil veritas est"
Words: 3
Nihil: 5 letters
Veritas: 7 letters
Est: 3 letters

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

public class words {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Please type a phrase.");
String phrase= in.nextLine();
StringTokenizer stoken = new StringTokenizer(phrase);
System.out.println("Your phrase has "+stoken.countTokens()+"words");


}

最佳答案

试试这个:

public class words {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Please type a phrase.");
String phrase= in.nextLine();

String[] words = phrase.split(" ");

System.out.println("The number of words is:"+words.length);

for(int i=0; i<words.length; i++){
System.out.println(words[i]+" is "+words[i].length()+" letters long.");

}
}
}

此代码使用 split() 而不是 Tokenizer。这对我来说似乎更容易。

关于JAVA:计算字符串上的每个单词,并计算单词上的每个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22360245/

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