Challenge: Finding the Longest Word
Завдання
Swipe to start coding
Write a program that finds the longest word in a string and outputs it along with the index of its first occurrence.
- The program should split the string into words and check the length of each word.
- For each word, compare its length with the length of the current longest word.
- If the current word is longer than the longest one, update the longest word and its index.
- Finally, output the result in the format:
"Longest word: [word] at index [index]"
, where[word]
is the longest word and[index]
is the index of its first occurrence in the string.
Рішення
solution
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.example;
public class Main {
public static void main(String[] args) {
String sentence = "I love programming in Java";
String result = findLongestWord(sentence);
System.out.println(result);
}
public static String findLongestWord(String sentence) {
String[] words = sentence.split(" ");
String longestWord = "";
int longestIndex = -1;
for (String word : words) {
if (word.length() > longestWord.length()) {
longestWord = word;
longestIndex = sentence.indexOf(word);
}
}
return "Longest word: \"" + longestWord + "\" at index " + longestIndex;
}
}
Все було зрозуміло?
Дякуємо за ваш відгук!
Секція 3. Розділ 5
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.example;
public class Main {
public static void main(String[] args) {
String sentence = "I love programming in Java";
String result = findLongestWord(sentence);
System.out.println(result);
}
public static String findLongestWord(String sentence) {
String[] words = ___.split(___);
String longestWord = "";
int longestIndex = -1;
for (String word : words) {
if (___.length() > longestWord.length()) {
longestWord = ___;
longestIndex = ___.indexOf(___);
}
}
return "Longest word: \"" + ___ + "\" at index " + ___;
}
}
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат