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?

有帮助吗?

解决方案

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().

其他提示

    return str.length() >= suffix.length() && str.substring(str.length() - suffix.length()) == suffix;

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

    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
    }
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

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.

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;

}

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;
}

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. :)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top