W3docs

How can I check if a single character appears in a string?

To check if a single character appears in a string in Java, you can use the indexOf method of the String class.

To check if a single character appears in a string in Java, you can use the indexOf method of the String class.

Here's an example of how you can use the indexOf method to check if a character appears in a string:

String s = "Hello, world!";
char c = 'o';

if (s.indexOf(c) >= 0) {
  // character appears in string
} else {
  // character does not appear in string
}

The indexOf method returns the index of the first occurrence of the character in the string, or -1 if the character does not appear in the string.

Alternatively, you can use the contains method of the String class to check if a character appears in a string:

String s = "Hello, world!";
char c = 'o';

if (s.contains(String.valueOf(c))) {
  // character appears in string
} else {
  // character does not appear in string
}

This will also check if the character appears in the string.

Note that the indexOf and contains methods are functionally equivalent for this task, but indexOf is generally preferred for single-character checks due to better performance, as it avoids the overhead of converting the character to a String.