How to check if a string ends with a char

The string starts with example will check if a string starts with a specified prefix while this example will check if a string ends with a char sequence. Each snippet will contain a String that represents a URL address and will validate that it ends with a #, pound sign, or anchor.

Straight up Java

This snippet will demonstrate how to use the String.endsWith method. The endsWith method will return true if the argument is the suffix of the String or false otherwise.

@Test
public void string_ends_with_java () {
    
    boolean isAnchor = "http://www.leveluplunch.com/#".endsWith("#");
    
    assertTrue(isAnchor);
}

Apache Commons

Apache commons StringUtils.endsWith will check if a CharSequence end with a specified suffix and returning true if it does, otherwise false.

Ends with

@Test
public void string_ends_with_apache_commons () {
    
    boolean isAnchor = StringUtils.endsWith("http://www.leveluplunch.com/#", "#");
    assertTrue(isAnchor);
}

Ends with any

Another useful method contained in apache commons is StringUtils.endsWithAny. This will perform the same behavior as the endsWith but instead of checking a single value, it will compare against a series of specified strings contained in the array.

@Test
public void string_ends_with_any_apache_commons () {

    boolean endsWithAnchorOrQ = StringUtils
            .endsWithAny("http://www.leveluplunch.com", new String[] {"#", "?"});
    
    assertFalse(endsWithAnchorOrQ);
}

Spring Framework

Each of the snippets above will compare with case sensitivity while the spring framework provides away to ignore upper and lower case. Calling the StringUtils.endsWithIgnoreCase will check if it ends with a character but is case insensitive.

@Test
public void string_ends_with_spring () {
    
    boolean isAnchor = 
            org.springframework.util.StringUtils
            .endsWithIgnoreCase("http://www.leveluplunch.com/#", "#");
    
    assertTrue(isAnchor);
}