In Java, you can find the last word in a `String` using various approaches. Here are some common methods:
Method 1: Using `split()`
public class LastWordExample { public static void main(String[] args) { String str = "Hello world from Java"; String[] words = str.trim().split("\\s+"); String lastWord = words[words.length - 1]; System.out.println("Last word: " + lastWord); } }
Output:
Last word: Java
Explanation:
– `trim()` removes leading and trailing spaces.
– `split(“\\s+”)` splits the string by spaces (handling multiple spaces).
– The last element of the array is accessed using `words.length – 1`.
Method 2: Using `lastIndexOf()` and `substring()`
public class LastWordExample { public static void main(String[] args) { String str = "Hello world from Java"; str = str.trim(); // Remove leading/trailing spaces int lastSpaceIndex = str.lastIndexOf(' '); String lastWord = (lastSpaceIndex == -1) ? str : str.substring(lastSpaceIndex + 1); System.out.println("Last word: " + lastWord); } }
Output:
Last word: Java
Explanation:
– `lastIndexOf(‘ ‘)` finds the last space in the string.
– `substring(lastSpaceIndex + 1)` extracts everything after the last space.
– If no space is found (`lastIndexOf` returns `-1`), the entire string is returned.
Method 3: Using `StringTokenizer`
import java.util.StringTokenizer; public class LastWordExample { public static void main(String[] args) { String str = "Hello world from Java"; StringTokenizer tokenizer = new StringTokenizer(str); String lastWord = ""; while (tokenizer.hasMoreTokens()) { lastWord = tokenizer.nextToken(); } System.out.println("Last word: " + lastWord); } }
Output:
Last word: Java
Explanation:
– `StringTokenizer` breaks the string into words.
– The last extracted word is stored in `lastWord`.
Method 4: Using Streams (Java 8+)
import java.util.Arrays; public class LastWordExample { public static void main(String[] args) { String str = "Hello world from Java"; String lastWord = Arrays.stream(str.trim().split("\\s+")) .reduce((first, second) -> second) .orElse(""); System.out.println("Last word: " + lastWord); } }
Output:
Last word: Java
Explanation:
`split(“\\s+”)` creates a stream of words.
`reduce((first, second) -> second)` keeps only the last word.