How can this Java code be improved to find sub-string in a string?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Most Java substring-search code can be simplified by using built-in string methods instead of custom nested loops. Better code is usually shorter, easier to test, and less prone to indexing bugs. This article shows practical improvements for one-off checks, repeated occurrence counting, case-insensitive matching, and performance-aware decisions.
Use Built-In Methods First
For simple existence checks, contains is the clearest API.
If you need position, use indexOf.
These methods are optimized and preferable to manual character loops in most cases.
Improve Repeated Match Counting
Custom counting loops often produce off-by-one mistakes. Use controlled indexOf stepping.
For overlapping matches, increment from by one instead of needle.length().
Case-Insensitive Search without Repeated Allocation
Case-insensitive search is often implemented inefficiently. Normalize once per input.
Using Locale.ROOT avoids locale-dependent surprises in certain languages.
Use Regex Only for Pattern Requirements
Regex is powerful but unnecessary for fixed substrings. Use regex only when you need wildcard-style matching or boundaries.
For literal matching, indexOf is simpler and generally faster.
Design Utility Methods with Clear Contracts
Improved code is not only about speed. Clear method contracts reduce future bugs.
Decide and document:
- how null input is handled
- whether empty needle is valid
- whether matching is case-sensitive
- whether overlap counts are expected
Example wrapper:
Explicit contracts make tests straightforward and behavior predictable.
Benchmark Before Introducing Complex Algorithms
Algorithms such as Boyer-Moore or Knuth-Morris-Pratt can help on very large workloads, but they increase implementation complexity.
Measure first:
If profiling does not show a real bottleneck, stick with standard methods.
Testing Scenarios to Include
Good substring utilities should be tested with:
- empty and null inputs
- needle longer than text
- repeated occurrences
- unicode strings
- case-insensitive edge cases
This prevents regressions when helper methods are reused across services.
Common Pitfalls
- Rewriting manual loops where
containsorindexOfalready solves the problem. - Ignoring null and empty-needle behavior in method contracts.
- Using regex for simple literal searches.
- Mixing overlapping and non-overlapping counting semantics.
- Optimizing algorithm complexity before profiling actual workloads.
Summary
- Prefer Java built-in string search methods for clarity and reliability.
- Use
indexOfloops for occurrence counting with explicit semantics. - Normalize text once for case-insensitive checks.
- Reserve regex and advanced algorithms for truly complex requirements.
- Define contracts and tests so substring logic remains maintainable.

