Using startsWith() and endsWith() in String

Using startsWith() and endsWith() in String class
Here is a dead simple tutorial on startsWith() and endsWith(). The startsWith() method is used to check if a string starts with a given string. The endsWith() method is used to check if a string ends with a given string. In a way, endsWith() can be used to check the extension of a file. But these are case-sensitive.


public boolean startsWith(String st)
public boolean endsWith(String st)

true is returned if the string object on which the method is called starts with/ends with st, false otherwise. Let us look at an example.


class StartsWithEndsWith
{
    public static void main(String args[])
    {
        // Use command line arguments, simply.
        String m=args[0];
      
        // Does m starts with foo
        System.out.println("Does m start with foo? (T/F) "+m.startsWith("foo"));
      
        // Does m end with bar
        System.out.println("Does m end with bar? (T/F) "+m.endsWith("bar"));
      
        // You can also use an assertion operator, alternatively.
        // m.startsWith("foo")?"m starts with foo":"m doesn't starts with foo";
      
        // To check irrespective of case (upper/lower)
        System.out.println("Does m start with foo (ignoring case) (T/F)? "+m.toLowerCase().startsWith("foo"));
      
        // Does m end with bar (ignore case)
        System.out.println("Does m end with bar (ignoring case) (T/F)? "+m.toLowerCase().endsWith("bar"));
    }
}

Sample Output


java StartsWithEndsWith FooBar

Does m start with foo? (T/F) false
Does m end with bar? (T/F) false
Does m start with foo (ignoring case) (T/F)? true
Does m end with bar (ignoring case) (T/F)? true

java StartsWithEndsWith FooABC

Does m start with foo? (T/F) false
Does m end with bar? (T/F) false
Does m start with foo (ignoring case) (T/F)? true
Does m end with bar (ignoring case) (T/F)? false

If you find this helpful, please share it. You might also like, converting string to byte array and char array and reversing a string.

No comments: