How to determine the last character

I have a string, and I want to know if the last character in my string has an #
Example:

String test="test my String #";
+3
source share
3 answers

Simply:

if (test.endsWith("#"))
+17
source

The following snippet should be instructive:

    String[] tests = {
        "asdf#",
        "#asdf",
        "sdf#f",
        "#",
        "",
        "asdf",
    };
    String fmt = "%6s%12s%12s%12s%n";
    System.out.format(fmt, "String", "startsWith", "endsWith", "contains");
    for (String test : tests) {
        System.out.format(fmt, test,
            test.startsWith("#"),
            test.endsWith("#"),
            test.contains("#")
        );
    }

Fingerprints:

String  startsWith    endsWith    contains
 asdf#       false        true        true
 #asdf        true       false        true
 sdf#f       false       false        true
     #        true        true        true
             false       false       false
  asdf       false       false       false

String API Links

+3
source
if(test.endsWith("#"))   

Or if you really want to do it manually (not a good idea) ...

if(test.charAt(test.length()-1) == '#')
+2
source

Source: https://habr.com/ru/post/1747555/


All Articles