Working with Java String Methods and Manipulations

Retrieving String Metadata

Length

To determine the total number of characters in a text sequennce, use the length() method:

text.length();

Searching Within Text

Character indices in Java strings range from 0 to length - 1.

  • indexOf(): Locates the first occurrence of a specific character or substring. Returns -1 if not found.
  • lastIndexOf(): Locates the final occurrence. Returns -1 if not found. Note that searching for an empty string "" typically returns the string's length.

Accessing Characters by Index

To retrieve a specific character at a given position, use charAt():

text.charAt(int position)

Example usage:

public class StringInspector {
    public static void main(String[] args) {
        String message = "hello world!";
        
        // Check length
        int size = message.length();
        System.out.println("Length: " + size);

        // Find first occurrence
        int firstL = message.indexOf('l');
        System.out.println("First 'l' at: " + firstL);

        // Find last occurrence
        int lastL = message.lastIndexOf('l');
        int emptySearch = message.lastIndexOf("");
        System.out.println("Last 'l' at: " + lastL);
        System.out.println("Empty search result: " + emptySearch);

        // Get character at specific index
        char specificChar = message.charAt(4);
        System.out.println("Char at 4: " + specificChar);
    }
}

Modifying and Comparing Strings

Extracting Substrings

  • substring(int start): Extracts text from the starting index to the end.
  • substring(int start, int stop): Extracts text between the start index (inclusive) and stop index (exclusive).

Trimming Whitespace

The trim() method removes leading and trailing spaces but preserves internal spaces.

Replacing Content

Use replace() to swap characters or substrings. It replaces all instances found within the text.

str.replace(char old, char new)

Prefix and Suffix Checks

  • startsWith(): Verifies if the string begins with a specific sequence.
  • endsWith(): Verifies if the string terminates with a specific sequence.

Equality Checks

Avoid using == for string comparison, as it checks memory references (addresses) rather than textual content. Instead, use:

  • equals(): Checks exact content match (case-sensitive).
  • equalsIgnoreCase(): Checks content match ignoring case differences.

Lexicographic Comparison

compareTo() compares two strings based on Unicode values. It returns a negative integer if the string comes before the argument, positive if after, and zero if equal.

Case Conversion

  • toLowerCase(): Converts all letters to lowercase (non-alphabetic characters remain unchanged).
  • toUpperCase(): Converts all letters to uppercase.

Splitting Strings

  • split(String regex): Divides the string into an array based on a delimiter.
  • split(String regex, int limit): Divides the string with a constraint on the resulting array size.

Example usage:

public class StringProcessor {
    public static void main(String[] args) {
        String data = " maybe this is an example ";

        // Substring extraction
        String part1 = data.substring(2);
        System.out.println(part1);

        String part2 = data.substring(2, 6);
        System.out.println(part2);

        // Trim spaces
        String trimmed = data.trim();
        System.out.println(trimmed);

        // Replace characters
        String replaced = data.replace("a", "b");
        System.out.println(replaced);

        // Check start and end
        System.out.println("Starts with space: " + data.startsWith(" "));
        System.out.println("Ends with 'z': " + data.endsWith("z"));

        // Equality
        String exactMatch = " maybe this is an example ";
        String caseDiff = " Maybe this is an EXAMPLE ";
        System.out.println("Equals: " + data.equals(exactMatch));
        System.out.println("Equals Ignore Case: " + data.equalsIgnoreCase(caseDiff));

        // Compare To
        System.out.println("Compare to case diff: " + data.compareTo(caseDiff));
        System.out.println("Compare to exact: " + data.compareTo(exactMatch));

        // Case conversion
        System.out.println("Upper: " + data.toUpperCase());

        // Splitting
        String[] segments = data.split(" ");
        String[] limitedSegments = data.split(" ", 3);

        for (String seg : segments) {
            System.out.println("[" + seg + "]");
        }
        
        for (String limSeg : limitedSegments) {
            System.out.println("{" + limSeg + "}");
        }
    }
}

Tags: java String Manipulation Methods Programming Basics Core Java

Posted on Sat, 09 May 2026 06:03:07 +0000 by Jramz