在Java中实现函数来计算字符串中每个单词的长度
发布时间:2023-06-26 06:00:29
在Java中,可以通过使用split()方法将字符串拆分成单独的单词,并使用该单词的长度来计算每个单词的长度。下面是一个实现该功能的示例代码:
public class WordLengthCalculator {
public static void main(String[] args) {
String sentence = "Hello world, how are you?";
int[] wordLengths = calculateWordLengths(sentence);
for(int i=0; i<wordLengths.length; i++) {
System.out.println("Length of word " + (i+1) + " : " + wordLengths[i]);
}
}
public static int[] calculateWordLengths(String sentence) {
String[] words = sentence.split(" ");
int[] wordLengths = new int[words.length];
for(int i=0; i<words.length; i++) {
wordLengths[i] = words[i].length();
}
return wordLengths;
}
}
在上面的代码中,calculateWordLengths()函数接收一个字符串作为参数,并使用split()方法将其拆分成单独的单词。然后,它创建一个整数数组来存储每个单词的长度,并遍历每个单词以计算其长度。最后,它返回这些长度作为一个整数数组。在示例代码的主函数中,我们使用了一个句子来测试calculateWordLengths()函数,并打印出每个单词的长度。
