SoFunction
Updated on 2025-04-21

Syntax, examples and application scenario analysis of Java string operation

introduction

In Java algorithm problems and daily development, string processing is a necessary core skill. This article comprehensively sorts out the common operation syntax of strings in Java, and combines code examples, application scenarios and pit avoidance guides to quickly master string processing skills and easily deal with high-frequency questions in written interviews.

1. Basic operations

1.1 Creating a String

// Method 1: Direct assignment (recommended)String s1 = "Hello";
// Method 2: ConstructorString s2 = new String("Hello");

Features

  • Direct assignment will reuse string constant pool objects, making memory more efficient
  • newA new object will be created with different addresses

1.2 Get the length

int len = ();  // 5

Application scenarios: traverse strings, empty operation
Notice: Empty string""The length is 0

1.3 Access characters

char c = (1);  // 'e'

Classic Applications: Pastoral string judgment

// Judgment palindrome examplepublic boolean isPalindrome(String s) {
    int left = 0, right = () - 1;
    while (left < right) {
        if ((left++) != (right--)) return false;
    }
    return true;
}

2. String processing

2.1 Substring Extraction

// Intercept from index 1 to endString sub1 = (1);   // "ello"
// Intercept indexes 1 to 3 (left closed and right open)String sub2 = (1, 3); // "el"

Application scenarios

  • Extract filename suffix
  • Parsing a specific format string (such as a date)

2.2 String stitching

// Method 1: + operator (compilation-time optimization)String s3 = s1 + " World!"; 
// Method 2: concat methodString s4 = (" World!");
// Method 3: StringBuilder (efficient)StringBuilder sb = new StringBuilder();
(s1).append(" World!");
String result = ();

Performance comparison

  • Single splicing:+More concise
  • Loop splicing: Must useStringBuilder

2.3 String search

// Find character positionsint index1 = ('e');       // 1
int lastIndex = ('l'); // 3
// Find the substring locationint index2 = ("llo");     // 2

Return value: Return index was found, return index was not found-1

2.4 String replacement

// Simple replacementString s5 = ('l', 'L'); // "HeLLo"
// Regular replacement (all vowels replaced by *)String s6 = ("[aeiou]", "*"); // "H*ll*"

Notice

  • replaceAllThe first parameter is a regular expression
  • Special characters need to be escaped, such asreplaceAll("\\+", "-")

3. Advanced Operation

3.1 String segmentation

// Split by commaString[] arr1 = "a,b,c".split(","); // ["a", "b", "c"]
// Split by point (requires escape)String[] arr2 = "".split("\\."); 

Application scenarios: Analyze CSV data, log analysis

3.2 Type conversion

// String ↔ Character arraychar[] chars = (); 
String s7 = new String(chars); 
// Other types → stringString s8 = (123);   // "123"
String s9 = (456); // "456"

3.3 Regular Match

// Verify that all numbers areboolean isNumber = "123".matches("\\d+"); // true
// Extract email formatString email = "test@";
boolean isValid = ("[a-zA-Z0-9]+@[a-z]+\\.[a-z]{2,3}");

Application scenarios: Data verification, format check

4. Performance optimization

4.1 Select the appropriate data structure

Scene Recommended Type reason
High frequency modification string StringBuilder Non-thread-safe but fast
Multi-threaded environment modification StringBuffer Thread safety
Read-only operation String Immutable features ensure safety

4.2 Efficient operation examples

Case: Inverting the string

// Method 1: StringBuilderpublic String reverse1(String s) {
    return new StringBuilder(s).reverse().toString();
}
// Method 2: Character arraypublic String reverse2(String s) {
    char[] arr = ();
    int left = 0, right =  - 1;
    while (left < right) {
        char temp = arr[left];
        arr[left++] = arr[right];
        arr[right--] = temp;
    }
    return new String(arr);
}

5. Summary

Key knowledge points

  • Immutability: The String object cannot be modified after creation, and the modification operation will generate a new object.
  • Comparative Principle: It is necessary to compare contentequals()==Compare object addresses
  • Performance Trap: Avoid using it in a loop+Stitching strings
  • Tool selection: Select String/StringBuilder/StringBuffer according to the scene

High-frequency algorithm application

  • String inversion: Use double pointers or StringBuilder
  • Substring search: KMP algorithm (can be combinedindexOfoptimization)
  • Bracket matching: stack + character traversal

Mastering these string operation techniques can significantly improve the resolution efficiency of algorithm problems. It is recommended to combine string classification questions from platforms such as LeetCode to conduct practical exercises (such asLeetCode 344. Invert string)。

This is the article about Java string operation full parsing: syntax, examples and application scenarios. For more related Java string operation content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!