Java String and indexOf
In Java, String.indexOf operates either naively or with JVM optimizations. For teaching purposes, the algorithm matters, not the internal intrinsic.
Characters are UTF-16 code units; be cautious with surrogates in real Unicode texts.
Where used
Everyday API in backends. For fixed patterns, often intrinsically optimized; still, you need to understand complexity and encoding (UTF-16).
Depth
String.indexOf searches for a character or a string from an optional starting position. The result is a position in Java's UTF-16 representation. Characters outside the Basic Multilingual Plane can consist of two code units, which is why the index and perceived character count can differ.
For repeated matches, you must consciously choose the next starting index. A shift by the pattern length will only find non-overlapping occurrences. A shift by one position allows overlaps but requires a special termination rule for an empty search string.
Difficulty levels
- Determine positions with and without the starting argument.
- Capture overlapping occurrences through appropriate shifting.
- Differentiate UTF-16 indices from Unicode code points.
Pitfalls
An unsuccessful result should not be used unchecked as an array or string position. Similarly, loops without secure progression for empty search strings can easily lead to non-termination.
Tasks
Card Info
- Topic: Algorithms and Data Structures
- Difficulty: Beginner
- Completed: 0 users