1

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?

2
  • 1
    "without the use of the built-in method" Why? Commented Apr 16, 2013 at 0:42
  • 1
    Hi Andrew, I was just honing my algo skills and got stuck. Commented Apr 16, 2013 at 0:46

8 Answers 8

2

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().
Sign up to request clarification or add additional context in comments.

11 Comments

Thanks Eng.Fouad! You solved it for me! Here is how I did it following your advice: public static boolean endsWithSuffix(String str, String suffix) { int n = suffix.length(); int nn = str.length()-n; if(suffix.length()<=str.length() && str.substring(nn, str.length()).equals(suffix)) { return true; } else { return false; } }
@Vitaly Well, I need a substring of str in order to check if it matches with the suffix, don't I?
@Dinky Creating a substring is more efficient than getting the char[] from the String, yes -- because String.toCharArray copies the char[]. But if you use String.charAt(int), there's no copying at all.
@yshavit Oh, I see. Thanks for clearing that up. So using String.charAt() would be more efficient, right?
@Dinky Comparing two int's and using built-in search method lastIndexOf() is the most efficient way.
|
2
    return str.length() >= suffix.length() && str.substring(str.length() - suffix.length()) == suffix;

you may use .equals but you have to add nullity check then

2 Comments

I did not know I could just return it like this. Thank you for the tip!
not a problem. Yes it will first check length and because of and operator it will not continue if first condition is not satisfied
2
    public static boolean endsWith(String str, String suffix){  
        return (str.lastIndexOf(suffix) == str.length() - suffix.length()); 
    }  

    public static void main(String[] args) {
        System.out.println(endsWith("this is a test", "test")); //True
        System.out.println(endsWith("This is another test", "test2"));  //False
    }

Comments

2

Since you're trying to re-invent the wheel for the sake of figuring out how a wheel works (which isn't a bad thing!), it seems like a bit of a cheat to use substring + equals, doesn't it? Why not just implement the check directly, rather than passing it off to equals?

The basic idea is to compare the last character of each string, then the second to last, then the third to last, etc. If you ever get an unequal comparison, you can return false. Otherwise, you can return true. In other words, you pair off the two strings, character-by-character; and rather than asking if those pairs are all equal, you ask whether any of them are un-equal.


Given an int i, you can get the "i-ith index from the right" via stringLength - 1 - i. For instance, the last digit is stringLength - 1, the second to last is stringLength - 2, etc. So:

  1. check whether the suffix is longer than str. If it is, you can return false
  2. let i represent how many chars from the right we want to look at
  3. Create a loop that will look at all the i-ith chars from the right within the suffix: for(int i = 0; i < suffix.length(); ++i)
  4. within each iteration, get the i-ith char from the right for both strings, as described above
  5. if they're unequal, return false. If they're equal, go on to the next iteration
  6. If you've exhausted all of the chars in suffix (ie, if the loop is finished), then return true.

Putting it all together:

public static boolean endsWithSuffix(String str, String suffix) {
    int strLen = str.length();
    int suffixLen = suffix.length();

    if (suffixLen > strLen)
        return false;
    for (int i = 0; i < suffixLen; ++i) {
        char strChar = str.charAt(strLen - 1 - i);
        char suffixChar = suffix.charAt(suffixLen - 1 - i);
        if (strChar != suffixChar)
            return false
    }
    return true
}

The initial check of suffixLen > strLen isn't just an optimization -- it's required for correctness. Otherwise, if the suffix is longer than the str, then the loop will go far enough that you'll be asking for str.charAt(-1) or even lower, which will raise an exception! There are other ways around solving this problem, but I'll leave it to you to find them. :)

1 Comment

Thank you for teaching me, yshavit! This is great stuff! Great explanation!
2
public static boolean endsWith(String test, String suffix) {

    int start = test.length() - suffix.length();
    if (start >= 0) {
        return test.indexOf(suffix, start) >= 0;
    }
    return false;
}

public static void main(String... args) {

    System.out.println(endsWith("aaabbbccc", "aaa"));
    System.out.println(endsWith("aaabbbccc", "bbb"));
    System.out.println(endsWith("aaabbbccc", "ccc"));
    System.out.println(endsWith("Hello Java", "Java"));
}

Output

false
false
true
true

5 Comments

Thanks for your input, Vitaly. How does this check if a string ends with a certain suffix? Doesn't this only check if the last index is greater than or equal to 0?
@Dinky No, I just forgot to add the suffix parameter, fixed.
Perhaps, " - 1" is not needed there. This answer is just an idea, working idea, however.
Let's say String str = "Hello Java"; and String suffix = "Java";. return str.lastIndexOf(suffix, str.length()-suffix.length()) >= 0 should return true and does return true. Could you enlighten me on how this works? I know that str.length()-suffix.length() = 6. So it's basically str.lastIndexOf("Java", 6) >= 0. How does this mechanism prove that "Hello Java" ends with "Java"?
You are right, it was wrong.. lastIndexOf should be indexOf. Answer updated with working and tested code.
1

Here's what I'd do:

  1. reverse the input String
  2. reverse the suffix String
  3. Check if the output of 1. String.startsWith the output of 2.

3 Comments

Thanks, tieTYT! Great answer but I wanted to stay away from startsWith() as well.
I figured you'd say that, but startsWith is straight forward to write on your own. Simply compare the output of 1. and 2. character by character.
@tieTYT Once you've got that insight, why not just do the same thing to write an endsWith? It's the same idea, just that instead of starting at 0 and incrementing, you start at s.length() - 1 and decrement.
1

you can try the Substring method for string

public static boolean endsWithSuffix(String str, String suffix) 
{
int a,b;
a=str.length();
b=suffix.length();
if (str.subString(b-a,a).equals(suffix))
   return true;
else 
   return false;

}

Comments

1

Try the following.

public static boolean endsWithSuffix(String str, String suffix)     
    int offset = str.length - suffix.length();
    if (offset >= 0) {
        String temp = str.substring(offset, str.length() - 1);
        if (suffix.equals(temp)) {
            return true;
        }
    }
    return false;
}

1 Comment

Thanks, Stephen. But shouldn't it be str.length() at the end of line 4?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.