tags:

views:

117

answers:

3

I have a string and i want to know if the last character in my string is #
example:

String test="test my String #";
+15  A: 

Simply:

if (test.endsWith("#"))
Jon Skeet
+2  A: 
if(test.endsWith("#"))   

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

if(test.charAt(test.length()-1) == '#')
froadie
taht is too late xD I also may be wrong but teh second could do harm for empty strings :(
Johannes Schaub - litb
Ehrm, charAt returns a char, does it not? So you should a) use `==` instead of `.equals` and b compare to `'#'` instead of `"#"`.
sepp2k
@Johannes - yeah and thought I was so fast can't compete with him :-/. @sepp2k - yup was a typo fixed it right away you read fast :)
froadie
+3  A: 

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("#")
        );
    }

This prints:

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

polygenelubricants