How to remove the last word from a string with Java

2 Answers

0 votes
public class RemoveTheLastWordFromAString {

    public static String removeLastWord(String s) {
        return s.substring(0, s.lastIndexOf(" "));
    }

    public static void main(String args[]) {
        String s = "java c c++ java python java";
    
        s = removeLastWord(s);
    
        System.out.println(s);
    }
}
 
      
/*
run:
      
java c c++ java python
    
*/

 



answered Oct 31, 2020 by avibootz
edited Mar 27 by avibootz
0 votes
public class RemoveTheLastWordFromAString {

    public static String removeLastWord(String s) {
        if (s == null || s.isEmpty())
            return s;

        // Remove trailing spaces
        s = s.replaceAll("\\s+$", "");

        if (s.isEmpty())
            return s;

        int lastSpace = s.lastIndexOf(' ');

        // If no space found, return original string
        if (lastSpace == -1)
            return s;

        return s.substring(0, lastSpace);
    }

    public static void main(String[] args) {
        String s;

        s = "java c c++ java python java";
        s = removeLastWord(s);
        System.out.println("1. " + s);

        s = "";
        s = removeLastWord(s);
        System.out.println("2. " + s);

        s = "c";
        s = removeLastWord(s);
        System.out.println("3. " + s);

        s = "c# java python ";
        s = removeLastWord(s);
        System.out.println("4. " + s);

        s = "  ";
        s = removeLastWord(s);
        System.out.println("5. " + s);
    }
}

 
      
/*
run:
      
1. java c c++ java python
2. 
3. c
4. c# java
5. 
    
*/

 



answered Mar 27 by avibootz
...