Search code examples
javaends-with

Removing parts of a string with endsWith


my goal here to remove the word "like" if it appears at the end of the users input which gets replicated as a string. But I am struggling to see what the problem is with my work.

When this is ran, anything before the word "like" is removed and I can't understand why so any advice would be appreciated, thanks in advance.

System.out.println("Type in an input, plez?");
String userInput4 = inputScanner.nextLine();
int userInput4Length = userInput4.length();
if (userInput4.toLowerCase().endsWith("like")) {
    String partOfString3 = userInput4.substring(userInput4Length- 4);
    System.out.println("There is a 'like' in your input, let me remove that for you:- " +partOfString3);
} else {
    System.out.println(userInput4);
}

Solution

  • substring() method's first parameter is beginIndex. So, you should write

    String partOfString3 = userInput4.substring(0, userInput4Length- 4);
    

    instead of

    String partOfString3 = userInput4.substring(userInput4Length- 4);