3

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

String test="test my String #"; 

3 Answers 3

17

Simply:

if (test.endsWith("#")) 
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

2
if(test.endsWith("#")) 

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

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

3 Comments

taht is too late xD I also may be wrong but teh second could do harm for empty strings :(
Ehrm, charAt returns a char, does it not? So you should a) use == instead of .equals and b compare to '#' instead of "#".
@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 :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.