Home > Enterprise >  Removing the last word from a String
Removing the last word from a String

Time:10-30

Given a String s= "This is a sample sentence" I want to produce the string "This is a sample". Is there a neat way to achieve this?

CodePudding user response:

This code was written by Github Copilot with minimal supervision:

    public static String removeLastWord(String s) {
        int endIndex = s.lastIndexOf(" ");
        return endIndex >= 0 ? s.substring(0, endIndex) : s;
    }

CodePudding user response:

Using regex:

s.replaceAll(" \\w $", "");
  •  Tags:  
  • java
  • Related