How can I check if a single character appears in a string?
In Java is there a way to check the condition:
"Does this single character appear at all in string x"
without using a loop?
You can use string.indexOf('a')
.
If the char a
is present in string
:
it returns the the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.
-
String.contains()
which checks if the string contains a specified sequence of char values -
String.indexOf()
which returns the index within the string of the first occurence of the specified character or substring (there are 4 variations of this method)