Search code examples
javastringends-with

How to implement String.endsWith() without using built-in method .endsWith() in Java


I am trying to implement String.endsWith() method without the use of the built-in method String.endsWith().

Here is my code:

public static boolean endsWithSuffix(String str, String suffix) {
    char[] chStr = str.toCharArray();
    char[] chSuf = suffix.toCharArray();

    if(!str.contains(suffix) {
        return false;
    }
    return true;
}

What is the best way to implement the endsWith() method without using the built-in method?

I've been trying with character arrays but no luck yet. Would strings be easier?


Solution

  • One way would be like this:

    • Check if suffix <= str.
    • Get the last n characters of str where n = suffix.length(), using substring().
    • Compare that portion of string with suffix with equals() or equalsIgnoreCase().