Explain Codes LogoExplain Codes Logo

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

java
linear-search
performance-implications
string-indexof
Nikita BarsukovbyNikita Barsukov·Dec 1, 2024
TLDR

To check whether a character appears in a string, leverage Java's built-in String.contains() method:

String str = "example"; char ch = 'a'; boolean containsChar = str.contains(String.valueOf(ch)); // Yields 'true' because, yes 'a' is chillin' out in "example"

Keep the fun, banish the boring: sidestep manual loops for the succinct magic provided by String.contains(CharSequence) & String.indexOf(Int).

Nimble-footed indexOf()

For a character's positional index (or -1 if the character is on a vacation), make use of String.indexOf():

String str = "hello"; char ch = 'e'; int charPos = str.indexOf(ch); // The 'what-spot-do-I-occupy?' method; returns 1 if 'e' is in town, else party pooper -1 boolean isPresent = charPos != -1;

No need to play catch, no Exception juggling here! This snippet does the job without any loop or recursion — it's all about the indexOf() hustle.

Recursion: The wall-crawler

Getting a Spidey sense for recursion? For pursuit of knowledge, here is a recursive way:

Recursive heads-up

Witness a recursive check in action:

public static boolean containsCharRecursively(String str, char ch, int index) { if (index >= str.length()) { return false; // Hit the wall? False alarm; no char here! } else if (str.charAt(index) == ch) { return true; // Hooray! Found our prodigal char } else { return containsCharRecursively(str, ch, index + 1); // Keep the search party moving } } String str = "recursion"; char ch = 's'; boolean contains = containsCharRecursively(str, ch, 0); // Let's ransack the string for 's'

This way is academic and less efficient than the wonder duo of indexOf/contains.

Decision parameters and trade-offs

(Catchy Matchy): String.contains() is your match made in heaven for a straightforward CharSequence.

(Ind(D)ex Finder Extraordinaire): Fancy the specifics of an index? String.indexOf() will not let you down!

(RegEx, the Pattern Adept): For matching complex patterns and characters, bow to the majesty of Regular Expressions — aka Regex.

Performance implications

Linear Search Party: Remember, indexOf and contains perform linear searches, similar to hide and seek. Their performance, in worst cases, is O(n). For big strings or repetitive operations, this can be a deal-breaker.

Special mentions and complications

Don't overlook these gotchas:

Null 'N Void Check: Stay alert for checking null strings or special char needing encoding.

The Unicode Conundrum: Unicode replete with surrogate pairs (like emoji) could be problematic with indexOf unless indexOfCodePoint comes for the rescue.

Speedy Gonzales: For performance-critical scenarios, dive into more advanced algorithms like Boyer-Moore or Knuth-Morris-Pratt (KMP).