SoFunction
Updated on 2025-03-04

Detailed explanation of string interception method in Java and summary of practical application

In Java, the common method of intercepting strings is to useStringClassicsubstringmethod. Apart fromsubstringMethods, there are other methods in Java that can be used to intercept strings, although these methods may not be as good assubstringDirect, but in some cases it may be more flexible or suitable for specific needs. For example: regular expressions,splitmethod,StringBuilderorStringBufferClass, third-party library Apache Commons Lang,StringTokenizerkind.

Use the substring method of the String class.

substringThere are two overloaded versions of the method:

substring(int beginIndex): Intercept the end of the string from the specified starting index.

substring(int beginIndex, int endIndex): Intercept the specified end index from the specified start index (excluding the end index).

Here are some sample code that shows how to use these two methods:

public class SubstringExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        // Intercept substrings from index 7 to the end of string        String substr1 = (7);
        ("Substring from index 7 to end: " + substr1); // Output: "World!"        // Intercept substrings from index 0 to index 5 (excluding 5)        String substr2 = (0, 5);
        ("Substring from index 0 to 5: " + substr2); // Output: "Hello"        // Intercept substrings from index 7 to index 12 (excluding 12)        String substr3 = (7, 12);
        ("Substring from index 7 to 12: " + substr3); // Output: "World"    }
}

Detailed explanation

substring(int beginIndex):

String substr1 = (7);

Starting from index 7, the end of the string is intercepted. The output result is"World!"

substring(int beginIndex, int endIndex):

String substr2 = (0, 5);

Intercept index 5 from index 0 (excluding 5).

The output result is"Hello"

String substr3 = (7, 12);

Index 12 is intercepted from index 7 (excluding 12).

The output result is"World"

Things to note

  • The index counts from 0.
  • beginIndexMust be greater than or equal to 0 and less than or equal to the length of the string.
  • endIndexMust be greater than or equal tobeginIndex, and less than or equal to the length of the string.
  • If the index is out of range, it will be thrownStringIndexOutOfBoundsExceptionabnormal.

Output of sample code

Run the above code and the output result is as follows:

Substring from index 7 to end: World!
Substring from index 0 to 5: Hello
Substring from index 7 to 12: World

Here are some alternatives:

Apart fromsubstringMethods, there are other methods in Java that can be used to intercept strings, although these methods may not be as good assubstringDirect, but in some cases it may be more flexible or suitable for specific needs.

Using regular expressions

Regular expressions can be used to match and extract specific parts of a string.

import ;
import ;
public class RegexExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        // Extract "World" using regular expression        Pattern pattern = ("World");
        Matcher matcher = (str);
        if (()) {
            String match = ();
            ("Matched substring: " + match); // Output: "World"        }
    }
}

Use String's split method

splitThe method can split the string into multiple substrings based on the specified delimiter, and then select the required part.

public class SplitExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        // Use commas and spaces as separators to split strings        String[] parts = (", ");
        // Extract the second part        if ( > 1) {
            String part = parts[1];
            ("Second part: " + part); // Output: "World!"        }
    }
}

Use StringBuilder or StringBuffer

In some cases, you may need to do more operations on the string, such as deleting or replacing characters, you can useStringBuilderorStringBufferkind.

public class StringBuilderExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        // Create a StringBuilder object        StringBuilder sb = new StringBuilder(str);
        // Delete the part from index 0 to index 7 (excluding 7)        (0, 7);
        // Convert the result to a string        String result = ();
        ("Resulting string: " + result); // Output: "World!"    }
}

Using the Apache Commons Lang library

If you can use third-party libraries, Apache Commons Lang provides a richer way to manipulate strings.

import .;
public class ApacheCommonsExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        // Substring method using Apache Commons Lang library        String substr = (str, 7, 12);
        ("Substring using Apache Commons: " + substr); // Output: "World"    }
}

Using StringTokenizer

StringTokenizerClasses can be used to split strings, although it is now deprecated, but may be seen in some old code.

import ;
public class StringTokenizerExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        // Use commas and spaces as separators        StringTokenizer tokenizer = new StringTokenizer(str, ", ");
        // Skip the first part        if (()) {
            ();
        }
        // Extract the second part        if (()) {
            String part = ();
            ("Second part using StringTokenizer: " + part); // Output: "World!"        }
    }
}

Some common scenarios and uses for intercepting and manipulating strings:

Data cleaning and preprocessing

When processing data, especially data obtained from files, databases or networks, often requires cleaning and pre-processing of strings. For example:

  • Extract specific information from log files.
  • Extract and verify data from user input.
  • Process and normalize text data, such as removing front and back spaces, converting upper and lower case, etc.

Search and replace

String search and replacement are very common operations, such as:

  • Find and replace specific words or phrases in the document.
  • Find and replace variable names or function names in the code.
  • Update the setting value in the configuration file.

Analyze and process

Parsing useful information from complex strings, for example:

  • Parses URL and query parameters.
  • Process files in CSV or other delimiter format.
  • Parses and processes JSON or XML strings.

Security and verification

In user input and data transmission, string operations can be used for security and verification, for example:

  • Verify email address, phone number and other formats.
  • Filter and escape special characters to prevent SQL injection or XSS attacks.
  • Analyze and verify JWT (JSON Web Tokens) and other authentication information.

Sample code

Here are some specific examples that show the application of string interception and operation in different scenarios:

Example 1: Extract the domain name from the URL

public class URLParser {
    public static void main(String[] args) {
        String url = "/path?query=123";
        // Extraction protocol        String protocol = (0, (":"));
        ("Protocol: " + protocol); // Output: "https"        // Extract the domain name        int start = ("://") + 3;
        int end = ("/", start);
        String domain = (start, end);
        ("Domain: " + domain); // Output: ""    }
}

Example 2: Format date string

import ;
import ;
public class DateFormatExample {
    public static void main(String[] args) {
        Date date = new Date();
        // Format dates using SimpleDateFormat        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = (date);
        ("Formatted Date: " + formattedDate); // Output: Current date and time    }
}

Example 3: Verify email address

public class EmailValidator {
    public static void main(String[] args) {
        String email = "user@";
        // Verify email address using simple regular expressions        boolean isValid = ("^[A-Za-z0-9+_.-]+@(.+)$");
        ("Is valid email: " + isValid); // Output: true    }
}

Example 4: Parsing CSV strings

public class CSVParser {
    public static void main(String[] args) {
        String csv = "John,Doe,30,New York";
        // Use split method to parse CSV string        String[] parts = (",");
        for (String part : parts) {
            (part);
        }
        // Output:        // John
        // Doe
        // 30
        // New York
    }
}

This is the article about the detailed explanation and practical application of string interception methods in Java. For more related Java string interception content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!