Java函数:找出字符串中最长的单词
发布时间:2023-06-05 13:23:39
在Java中,我们可以使用字符串函数和循环来找出一个字符串中最长的单词。
步骤:
1. 首先,我们需要这个字符串的长度,通过使用字符串函数length(),我们可以得到字符串的长度。
2. 然后,我们需要将这个字符串转成一个字符数组,这样我们可以对每个字符进行遍历。
3. 接着,我们需要定义一个变量来存储最长的单词,我们先把这个变量设置为空。
4. 然后,我们需要用循环遍历每个字符,如果这个字符是字母,则开始读取这个单词,并把它存储到一个变量中。
5. 如果我们遍历到一个空格,则认为这个单词结束了,我们比较当前单词的长度,如果它比已经存储的最长单词的长度长,则更新这个最长单词的变量。
6. 最后,我们把最长的单词输出。
示例代码:
public static String findLongestWord(String str) {
int len = str.length(); // 获取字符串长度
char[] arr = str.toCharArray(); // 把字符串转成字符数组
String longest_word = ""; // 定义一个变量来存储最长的单词
String current_word = ""; // 定义一个变量来存储当前单词
for(int i=0; i<len; i++) {
if(Character.isLetter(arr[i])) { // 如果这个字符是字母,则开始读取这个单词
current_word += arr[i]; // 把它存储到一个变量中
} else { // 如果我们遍历到一个空格,则认为这个单词结束了
if(current_word.length() > longest_word.length()) { // 比较当前单词的长度
longest_word = current_word; // 如果它比已经存储的最长单词的长度长,则更新这个最长单词的变量
}
current_word = ""; // 重置当前单词
}
}
return longest_word; // 返回最长的单词
}
在测试代码中,我们可以使用这个函数来测试不同的字符串:
public static void main(String[] args) {
String str1 = "Hello World"; // 最长的单词是Hello
String str2 = "The quick brown fox jumps over the lazy dog"; // 最长的单词是jumps
String str3 = "Sphinx of black quartz, judge my vow"; // 最长的单词是quartz
System.out.println(findLongestWord(str1)); // 输出"Hello"
System.out.println(findLongestWord(str2)); // 输出"jumps"
System.out.println(findLongestWord(str3)); // 输出"quartz"
}
在这个例子中,我们可以看到最长的单词分别是“Hello”,“jumps”和“quartz”。
