Popular Searches
Popular Course Categories
Popular Courses

Performing String Searching, Replacing, and Splitting

Performing String Searching, Replacing, and Splitting

Strings and String Manipulation

Performing String Searching, Replacing, and Splitting in Java

Course: Core Java Training

Topic: Performing String Searching, Replacing, and Splitting

Course Link: Core Java Training Course

Demo Link: Register for a Free Course Demo

JustAcademy Homepage: Visit JustAcademy


1. Introduction

Strings are widely used in Java to store and process text, including names, email addresses, messages, product descriptions, log entries, and user input. In many applications, developers need to find a particular character or word, replace unwanted text, or divide a sentence into smaller parts. Java provides built-in methods in the String class to perform these operations.

String searching helps locate characters or sequences of characters. Replacing creates a string with selected characters or matching text changed. Splitting divides a string into an array of smaller strings based on a delimiter or regular expression.

Learning Objectives

  • Understand common String searching methods.
  • Find characters and substrings using indexOf(), lastIndexOf(), and contains().
  • Check the beginning and ending of strings using startsWith() and endsWith().
  • Replace characters and matching text using replace(), replaceAll(), and replaceFirst().
  • Split strings into arrays using split().
  • Understand regular expressions, delimiters, edge cases, and common errors.
  • Apply string-processing techniques to practical Java programs.

2. Understanding String Searching

String searching means checking whether a character or substring exists in a string and, when needed, finding its position. Java provides several methods for these tasks.

2.1 The indexOf() Method

The indexOf() method returns the index of the first occurrence of a character or substring. Java string indexes start at 0. If the requested character or substring is not found, the method returns -1.

public class IndexOfExample {
    public static void main(String[] args) {
        String message = "Learn Java Programming";

        System.out.println(message.indexOf('a'));
        System.out.println(message.indexOf("Java"));
        System.out.println(message.indexOf("Python"));
        System.out.println(message.indexOf('a', 5));
    }
}

Explanation:

  • indexOf('a') returns the index of the first lowercase a.
  • indexOf("Java") returns the starting index of the substring Java.
  • indexOf("Python") returns -1 because the substring does not exist.
  • indexOf('a', 5) starts searching from index 5.

2.2 The lastIndexOf() Method

The lastIndexOf() method finds the last occurrence of a character or substring. It is useful when a character appears multiple times and the final occurrence is needed.

public class LastIndexOfExample {
    public static void main(String[] args) {
        String text = "java is easy and java is powerful";

        System.out.println(text.indexOf("java"));
        System.out.println(text.lastIndexOf("java"));
        System.out.println(text.lastIndexOf('a'));
    }
}

Key point: indexOf() searches for the first occurrence, while lastIndexOf() searches for the last occurrence. Both return -1 when no match exists.

2.3 The contains() Method

The contains() method checks whether a string contains a specified character sequence. It returns a boolean value: true if the sequence is found and false otherwise.

public class ContainsExample {
    public static void main(String[] args) {
        String email = "[email protected]";

        System.out.println(email.contains("@"));
        System.out.println(email.contains("example"));
        System.out.println(email.contains("gmail"));
    }
}

This method is useful for basic text checks. However, checking whether an email contains an @ symbol is not enough to fully validate an email address.

2.4 The startsWith() and endsWith() Methods

These methods check whether a string begins or ends with a particular sequence of characters.

public class PrefixSuffixExample {
    public static void main(String[] args) {
        String fileName = "report.pdf";
        String website = "https://example.com";

        System.out.println(fileName.startsWith("report"));
        System.out.println(fileName.endsWith(".pdf"));
        System.out.println(website.startsWith("https://"));
    }
}

These methods are useful for checking file extensions, URL prefixes, naming conventions, and other predictable text patterns.

2.5 Case Sensitivity in Searching

Most standard String searching methods are case-sensitive. Therefore, "Java" and "java" are treated as different sequences.

String language = "Java Programming";

System.out.println(language.contains("Java")); // true
System.out.println(language.contains("java")); // false

For a simple case-insensitive search, normalize both strings using the same case. Use Locale.ROOT when applying locale-independent case conversion.

import java.util.Locale;

String text = "Java Programming";
String searchTerm = "JAVA";

boolean found = text.toLowerCase(Locale.ROOT)
                    .contains(searchTerm.toLowerCase(Locale.ROOT));

System.out.println(found); // true

For advanced linguistic or Unicode-aware text matching, simple lowercasing may not be sufficient; the appropriate approach depends on the application's language and requirements.


3. Understanding String Replacing

String replacement means creating a new string in which selected characters or matching text are changed. Since Java strings are immutable, replacement methods do not modify the original string. They return a new string containing the result.

3.1 The replace() Method

The replace() method replaces all occurrences of a specified literal character or character sequence. It does not interpret the target as a regular expression.

public class ReplaceExample {
    public static void main(String[] args) {
        String message = "Java is fun. Java is useful.";

        String updated = message.replace("Java", "Core Java");

        System.out.println("Original: " + message);
        System.out.println("Updated: " + updated);
    }
}

Explanation: Every occurrence of the literal text Java is replaced with Core Java. The original variable still refers to the unchanged string.

3.2 Replacing Characters

The same method can replace one character with another character.

public class ReplaceCharacterExample {
    public static void main(String[] args) {
        String phone = "987-654-3210";

        String digitsOnly = phone.replace("-", "");

        System.out.println(digitsOnly);
    }
}

This example removes every hyphen from the string. Similar operations can normalize simple formatting in identifiers, phone numbers, or input text, provided the transformation is appropriate for the data.

3.3 The replaceFirst() Method

The replaceFirst() method replaces only the first match of a regular expression. Unlike replace(), its first argument is interpreted as a regex pattern.

public class ReplaceFirstExample {
    public static void main(String[] args) {
        String text = "red blue red green";

        String result = text.replaceFirst("red", "black");

        System.out.println(result);
    }
}

Output:

black blue red green

3.4 The replaceAll() Method

The replaceAll() method replaces every match of a regular expression. It is useful when the target is a pattern rather than a fixed literal string.

public class ReplaceAllExample {
    public static void main(String[] args) {
        String text = "Java   is    easy";

        String result = text.replaceAll("\\s+", " ");

        System.out.println(result);
    }
}

Output:

Java is easy

In this example, \\s+ is a Java string containing the regex pattern \s+. The pattern matches one or more whitespace characters, which are replaced by a single space.

3.5 Difference Between replace(), replaceFirst(), and replaceAll()

Method First Argument Replacement Scope Typical Use
replace() Literal character or sequence All literal occurrences Replacing a word or character
replaceFirst() Regular expression First regex match only Changing the first matching pattern
replaceAll() Regular expression Every regex match Normalizing whitespace or patterns

3.6 Replacing Special Characters Safely

Regular expressions assign special meanings to characters such as ., *, +, ?, [, and (). If a pattern should match a literal special character, escape it appropriately or use Pattern.quote() to quote the pattern.

import java.util.regex.Pattern;

public class SpecialCharacterExample {
    public static void main(String[] args) {
        String text = "price is $50 and $75";
        String symbol = "$";

        String result = text.replaceAll(
            Pattern.quote(symbol),
            "USD "
        );

        System.out.println(result);
    }
}

Important: In regex-based replacement methods, the replacement string also has special rules for characters such as $ and backslash. When inserting arbitrary user-provided replacement text, consider Matcher.quoteReplacement() to prevent those characters from being interpreted specially.


4. Understanding String Splitting

The split() method divides a string into an array of strings using a regular expression as the delimiter. It is commonly used to process comma-separated values, words, simple records, and structured input.

4.1 Basic Use of split()

import java.util.Arrays;

public class SplitExample {
    public static void main(String[] args) {
        String languages = "Java,Python,JavaScript";

        String[] items = languages.split(",");

        System.out.println(Arrays.toString(items));
    }
}

Output:

[Java, Python, JavaScript]

The comma is treated as the delimiter. The returned value is a String[], so each element can be accessed by its index or processed using a loop.

4.2 Splitting a Sentence by Whitespace

import java.util.Arrays;

public class SplitWordsExample {
    public static void main(String[] args) {
        String sentence = "Java   makes coding easier";

        String[] words = sentence.trim().split("\\s+");

        System.out.println(Arrays.toString(words));
    }
}

The regular expression \\s+ matches one or more whitespace characters. The trim() call removes leading and trailing characters recognized by that method before splitting. For broader Unicode whitespace handling, choose a pattern and normalization approach that matches the application's needs.

4.3 Splitting by a Dot or Other Regex Metacharacter

The dot (.) has a special meaning in regular expressions: it matches almost any single character. To split using a literal dot, escape it in the regex. Java string literals require an additional backslash.

import java.util.Arrays;

public class SplitFileNameExample {
    public static void main(String[] args) {
        String fileName = "report.final.pdf";

        String[] parts = fileName.split("\\.");

        System.out.println(Arrays.toString(parts));
    }
}

Output:

[report, final, pdf]

For a literal delimiter that may contain regex metacharacters, use Pattern.quote(delimiter) to avoid manually escaping it.

4.4 Using the Limit Parameter

The overloaded split(regex, limit) method controls how many parts are returned and how trailing empty strings are handled.

Limit Value Behavior
Positive value Applies the pattern at most limit minus one times, so the result contains no more than the specified number of elements.
0 Splits as needed and removes trailing empty strings from the result.
Negative value Splits as needed and preserves trailing empty strings.
import java.util.Arrays;

public class SplitLimitExample {
    public static void main(String[] args) {
        String data = "name,department,location";

        System.out.println(Arrays.toString(data.split(",", 2)));
        System.out.println(Arrays.toString("a,b,,".split(",")));
        System.out.println(Arrays.toString("a,b,,".split(",", -1)));
    }
}

The first example produces two parts, with the second part containing the remaining text. The second example drops trailing empty fields, while the third preserves them. This distinction matters when empty fields carry meaning in a data record.

4.5 Iterating Through a Split String

public class SplitLoopExample {
    public static void main(String[] args) {
        String subjects = "Java,SQL,Spring";

        String[] subjectArray = subjects.split(",");

        for (String subject : subjectArray) {
            System.out.println(subject);
        }
    }
}

A for-each loop is a simple way to process each part of the resulting array.

4.6 Handling Empty or Missing Input

Before splitting user-provided data, decide how the application should handle null, empty, or malformed input. Calling a method on a null reference causes a NullPointerException.

public class SafeSplitExample {
    public static void main(String[] args) {
        String input = "";

        if (input == null || input.isEmpty()) {
            System.out.println("No input provided.");
        } else {
            String[] parts = input.split(",");
            System.out.println("Parts: " + parts.length);
        }
    }
}

For real applications, validate input according to the expected format. The basic split() method is not a complete CSV parser: quoted fields, embedded commas, escaped quotes, and line breaks require a CSV-aware library or a carefully designed parser.


5. Combining Searching, Replacing, and Splitting

These methods can be combined to prepare text for further processing. For example, a program may check for a keyword, normalize repeated whitespace, and then split the sentence into words.

import java.util.Arrays;

public class TextProcessingExample {
    public static void main(String[] args) {
        String text = "Java   is powerful and Java is popular";

        // Search for a keyword
        if (text.contains("Java")) {
            System.out.println("Keyword found");
        }

        // Normalize repeated whitespace
        String normalized = text.replaceAll("\\s+", " ").trim();

        // Split into words
        String[] words = normalized.split(" ");

        System.out.println("Normalized: " + normalized);
        System.out.println("Words: " + Arrays.toString(words));
        System.out.println("Word count: " + words.length);
    }
}

Step-by-Step Execution

  1. The program searches for the literal substring Java.
  2. It replaces each run of whitespace with a single space.
  3. It trims leading and trailing whitespace.
  4. It splits the normalized sentence into an array of words.
  5. It displays the processed sentence, array, and word count.

6. Practical Example: Searching and Masking Sensitive Text

The following example demonstrates how to find a substring and replace a specific literal sequence. It is a learning example, not a complete data-security or privacy solution.

public class TextMaskingExample {
    public static void main(String[] args) {
        String message = "Reference ID: AB12345. Status: Pending.";

        if (message.contains("AB12345")) {
            String masked = message.replace("AB12345", "******");
            System.out.println(masked);
        } else {
            System.out.println("Reference ID not found.");
        }
    }
}

For production systems, avoid logging sensitive values unnecessarily and use a masking strategy designed for the actual data format.


7. Important Differences and Best Practices

Requirement Recommended Method Reason
Find the first occurrence indexOf() Returns the first matching index.
Find the last occurrence lastIndexOf() Returns the last matching index.
Check for a substring contains() Returns a boolean result.
Replace literal text everywhere replace() Does not treat the target as regex.
Replace only the first regex match replaceFirst() Changes only the first pattern match.
Replace all regex matches replaceAll() Applies the pattern throughout the string.
Divide text into pieces split() Returns an array based on a regex delimiter.

Best Practices

  • Remember that string indexes begin at zero.
  • Check for -1 when using indexOf() or lastIndexOf().
  • Use replace() for literal replacements and regex methods only when pattern matching is required.
  • Escape regex metacharacters or use Pattern.quote() for literal delimiters.
  • Use the split limit parameter when trailing empty fields or the maximum number of parts matter.
  • Check for null values before calling String methods.
  • Remember that String methods return results; they do not mutate the original String object.
  • Use meaningful variable names such as searchTerm, normalizedText, and parts.
  • Do not assume simple substring checks provide complete validation of emails, URLs, or other structured data.
  • Use a dedicated parser for structured formats such as CSV when quoting and escaping rules are involved.

8. Common Errors and Troubleshooting

Problem Cause Solution
Search result is -1 Text was not found or capitalization differs. Verify the search term and check case sensitivity.
Replacement changes unexpected text A regex method interprets the pattern specially. Use replace() for literal replacement or quote the regex.
Split does not work with a dot The dot is a regex metacharacter. Use split("\\.") or quote the delimiter.
Trailing empty values disappear The default split behavior removes trailing empty strings. Use split(regex, -1) when those fields must be retained.
NullPointerException The source string is null. Validate the reference before calling a method.
Original text appears unchanged The returned result was not stored or used. Assign the result to a variable or use it directly.
Replacement text with dollar signs behaves unexpectedly Regex replacement syntax interprets special replacement characters. Use Matcher.quoteReplacement() for literal replacement text in regex-based methods.

9. Practice Exercises

  1. Write a program that finds the first and last occurrence of the letter a in a sentence.
  2. Ask the user for a word and check whether a given sentence contains it.
  3. Write a program that replaces every occurrence of Java with Core Java.
  4. Replace multiple consecutive spaces with one space using replaceAll().
  5. Split a comma-separated list of programming languages and print each language on a separate line.
  6. Split a file name by a literal dot and display each part.
  7. Compare the outputs of split(",") and split(",", -1) for a string with trailing commas.
  8. Build a program that checks whether a message contains a keyword, normalizes whitespace, and counts the resulting words.

Mini Project: Text Analyzer

Objective: Build a simple program that searches, replaces, and splits a user-provided sentence.

Requirements:

  • Store a sample sentence or read a sentence from the user.
  • Ask for a search term and report whether it exists.
  • Display the index of its first occurrence when found.
  • Replace a selected word with another word.
  • Normalize repeated whitespace.
  • Split the final sentence into words and display the word count.
  • Handle empty input and explain what happens if the search term is not found.

Expected learning outcome: Students should be able to select suitable String methods, understand regex-based operations, and process text reliably.


10. Core Java Interview Questions and Answers

Q1. What is the purpose of indexOf()?

Answer: It returns the index of the first occurrence of a specified character or substring. It returns -1 when no match exists.

Q2. What is the difference between indexOf() and lastIndexOf()?

Answer: indexOf() finds the first occurrence, whereas lastIndexOf() finds the last occurrence.

Q3. What does contains() return?

Answer: It returns true if the specified character sequence occurs in the string; otherwise, it returns false.

Q4. What is the difference between replace() and replaceAll()?

Answer: replace() replaces literal character sequences, while replaceAll() interprets its first argument as a regular expression and replaces all matches.

Q5. What does replaceFirst() do?

Answer: It replaces only the first match of a regular expression.

Q6. Why is split("\\.") used to split a file name by dots?

Answer: A dot has a special meaning in regex, so the backslash escapes it. The extra backslash is required because Java string literals also use backslashes for escaping.

Q7. What is the return type of split()?

Answer: It returns an array of strings, represented by String[].

Q8. Why might trailing empty strings disappear after splitting?

Answer: The one-argument split() method behaves like split(regex, 0), which discards trailing empty strings. A negative limit preserves them.

Q9. Do String replacement methods modify the original string?

Answer: No. Strings are immutable. Replacement methods return a new string containing the result.

Q10. When should a developer avoid using split() for CSV data?

Answer: When CSV fields may contain quoted commas, escaped quotes, or embedded line breaks. A CSV-aware parser should be used for such input.


11. Quick Revision Checklist

  • indexOf() finds the first occurrence.
  • lastIndexOf() finds the last occurrence.
  • contains() checks whether a substring exists.
  • startsWith() and endsWith() check prefixes and suffixes.
  • replace() performs literal replacement.
  • replaceFirst() replaces the first regex match.
  • replaceAll() replaces every regex match.
  • split() divides text into a String[] using a regex delimiter.
  • split(regex, -1) preserves trailing empty strings.
  • String methods do not modify the original String object.
  • Regex patterns and regex replacement strings have special escaping rules.

12. Conclusion

String searching, replacing, and splitting are essential skills in Core Java. Methods such as indexOf(), contains(), replace(), replaceAll(), and split() help developers inspect and transform text in a clear and reusable way. By understanding case sensitivity, regular expressions, split limits, string immutability, and input validation, developers can avoid common errors and build more reliable Java applications.

To continue learning Java fundamentals and practice additional programming concepts, visit the JustAcademy Core Java Training Course, explore the course demo registration page, or visit the JustAcademy homepage.

whatsapp