You can extract the last word from a string in Java using a `for` loop. Below is an example demonstrating how to achieve this:
Example:
public class LastWordExample {
public static void main(String[] args) {
String str = "Hello World from Java";
String lastWord = "";
str = str.trim(); // Remove leading/trailing spaces
int length = str.length();
// Loop backward to find the last word
for (int i = length - 1; i >= 0; i--) {
if (str.charAt(i) == ' ') {
break; // Stop when a space is encountered
}
lastWord = str.charAt(i) + lastWord; // Prepend character to form the word
}
System.out.println("Last word: " + lastWord);
}
}
Explanation:
1. Trim the string to remove unnecessary spaces.
2. Loop from the end of the string towards the beginning.
3. Check for a space (`' '`):
- If found, stop the loop (we have found the last word).
- Otherwise, prepend characters to form the last word.
4. Print the last word.
Output:
Last word: JavaThis approach ensures that even if there are multiple spaces at the end, the correct last word is extracted.