Use String.indexOf
:
int pos = str.indexOf('*');
if (pos == 0) {
// Found at beginning.
} else if (pos == str.length() - 1) {
// Found at end.
} else if (pos > 0) {
// Found in middle.
}
An alternative would be to use startsWith
/endsWith
/contains
:
if (str.startsWith('*')) {
// Found at beginning.
} else if (str.endsWith('*')) {
// Found at end.
} else if (str.contains('*')) {
// Found in middle.
}
which might be marginally more efficient, since it avoids having to check the entire string in the case that it ends with *
. However, readability of the code should be the primary concern in selecting between these two, since the performance difference would be negligible in many cases.
And, of course, you don't get the actual position of the *
if you use the latter approach. It depends upon what you are really trying to do as to whether that matters.