How to get the last word of a string in Java

1 Answer

0 votes
public class Main {

    // Returns the last word from a string.
    // Empty or whitespace-only strings return an empty string.
    public static String getLastWord(String input) {
        if (input == null || input.isBlank()) {
            return "";
        }

        // Trim leading/trailing whitespace
        String trimmed = input.trim();

        // Split on whitespace
        String[] parts = trimmed.split("\\s+");

        // Return the last element
        return parts[parts.length - 1];
    }

    public static void main(String[] args) {
        String[] tests = {
            "vb.net javascript php c c# python c++",
            "",
            "c#",
            "c c++ java ",
            "  "
        };

        for (int i = 0; i < tests.length; i++) {
            System.out.println((i + 1) + ". " + getLastWord(tests[i]));
        }
    }
}



/*
run:

1. c++
2. 
3. c#
4. java
5. 

*/

 



answered Mar 27 by avibootz
...