We have a string input and the following combinations are valid (e.g. sunday
, *sunday*
, sun*day*
, *sun*day
, su*nda*y
)
If it contains only a single asterisk, then it is a bad input.
So given the above input, how do I check to see if the string contains multiple asterisks.
int asterisk1 = input.indexOf('*');
boolean hasTowAsterisks = asterisk1 != -1 && input.indexOf('*', asterisk1+1) != -1;
Edit: this solution assumed that the requirement was "has at least two asterisks".
You could use String.matches
with a regular expression:
"^.*(?:\\*.*){2}$"
If you want exactly two asterisks:
"^[^*]*(?:\\*[^*]*){2}$"
Though for this task it might be simpler just to iterate over the string and count the asterisks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With