I am just wondering if it is possible to check a string for specific characters. For example if my string is String mystr = "test"; and I wanted to check for the letter t at the beginning and if it is NOT there do something how would I go about this?

I have read about string.startsWith(string2); however it returns true or false, I want to be able to do "XYZ" if "ABC" isn't satisfied, and it would seem that string.contains isn't a thing.

To paraphrase, I am trying to create an if statement that will evaluate if a string starts with a certain character(s) and will do something if this condition is NOT met.

  • In C and C++, the ! operator means “not”. E.g. if (!(the condition)) { some_action(); } means “do some action if the condition is not satisfied”. – Edgar Bonet Sep 9 '16 at 19:47
  • Yes! I thought that I might be able to adapt the string.startsWith, however it flagged saying expected unqualified id before '!' token – user26383 Sep 9 '16 at 23:04
  • What did you write to get that error? If you don't show us your code, we won't be able to help. – Edgar Bonet Sep 10 '16 at 7:40
  • I messed up and put the ! in the wrong place, sorry to have not caught that. – user26383 Sep 10 '16 at 17:01

Have you tried the following?

if(!actualString.startsWith(expectedString)) {
  // do whatever you have to

BTW, that is what actually suggested in @EdgarBonet's comment.

| improve this answer | |
  • That did it, I had the ! in the wrong place. – user26383 Sep 10 '16 at 17:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.