Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Challenge: Finding the Longest Word | String Advanced
Java Extended

book
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.

  1. The program should split the string into words and check the length of each word.
  2. For each word, compare its length with the length of the current longest word.
  3. If the current word is longer than the longest one, update the longest word and its index.
  4. 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.

Рішення

java

solution

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
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 " + ___;
}
}

Запитати АІ

expand
ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

some-alt