杰瑞科技汇

Java中replace替换字符串为何不生效?

Of course! In Java, there are several ways to replace parts of a String. The method you choose depends on whether you need to replace a single occurrence, all occurrences, or if you're dealing with complex patterns.

Java中replace替换字符串为何不生效?-图1
(图片来源网络,侵删)

Here’s a complete guide, from the simplest methods to more advanced techniques.


The replace() Method (Most Common)

This is the most straightforward method for replacing literal characters or substrings. It comes in two flavors:

replace(char oldChar, char newChar)

Replaces all occurrences of a single character with another character.

Example:

Java中replace替换字符串为何不生效?-图2
(图片来源网络,侵删)
public class ReplaceExample {
    public static void main(String[] args) {
        String str = "hello world";
        // Replace all 'l's with 'p's
        String newStr = str.replace('l', 'p');
        System.out.println("Original string: " + str);
        System.out.println("New string:      " + newStr); // Output: "heppo worpd"
    }
}

replace(CharSequence target, CharSequence replacement)

Replaces all occurrences of a literal substring (target) with another substring (replacement). This is the most frequently used method for string replacement.

Example:

public class ReplaceSubstringExample {
    public static void main(String[] args) {
        String str = "I like Java. Java is powerful.";
        // Replace all occurrences of "Java" with "Python"
        String newStr = str.replace("Java", "Python");
        System.out.println("Original string: " + str);
        System.out.println("New string:      " + newStr);
        // Output: "I like Python. Python is powerful."
    }
}

The replaceFirst() Method

This method is useful when you only want to replace the first occurrence of a pattern. It uses regular expressions for its search pattern.

replaceFirst(String regex, String replacement)

Replaces the first subsequence of the input sequence that matches the regular expression regex with the given replacement.

Java中replace替换字符串为何不生效?-图3
(图片来源网络,侵删)

Example:

public class ReplaceFirstExample {
    public static void main(String[] args) {
        String str = "one two one two one";
        // Replace only the first occurrence of "one"
        String newStr = str.replaceFirst("one", "1");
        System.out.println("Original string: " + str);
        System.out.println("New string:      " + newStr);
        // Output: "1 two one two one"
    }
}

The replaceAll() Method

This method is powerful because it uses regular expressions (regex) to find patterns to replace, not just literal strings. It replaces all occurrences.

replaceAll(String regex, String replacement)

Replaces every subsequence of the input sequence that matches the regular expression regex with the given replacement.

Example 1: Simple Replacement (same as replace())

String str = "hello world";
// This works the same as str.replace("l", "p");
String newStr = str.replaceAll("l", "p"); 
// Output: "heppo worpd"

Example 2: Using Regex for More Powerful Replacement Let's say you want to remove all digits from a string.

public class ReplaceAllRegexExample {
    public static void main(String[] args) {
        String str = "Order 12345 received on 12/05/2025.";
        // Replace any sequence of one or more digits (\d+) with an empty string ""
        String newStr = str.replaceAll("\\d+", "");
        System.out.println("Original string: " + str);
        System.out.println("New string:      " + newStr);
        // Output: "Order  received on /."
        // A better version to clean up extra spaces:
        String cleanStr = newStr.replaceAll("\\s+", " ").trim();
        System.out.println("Cleaned string:  " + cleanStr);
        // Output: "Order received on /."
    }
}

Important Note: Since the backslash \ is an escape character in both Java strings and regex, you need to use \\ to represent a single literal backslash in your regex pattern. For example, \d (digit) becomes "\\d" in a Java string.


Advanced: Using StringBuilder for Performance

If you are performing many string replacements or modifications in a loop, repeatedly creating new String objects can be inefficient. StringBuilder is mutable and is designed for this kind of work.

Example:

public class StringBuilderExample {
    public static void main(String[] args) {
        String original = "the quick brown fox jumps over the lazy dog";
        StringBuilder sb = new StringBuilder(original);
        // replace() in StringBuilder replaces a character sequence within the builder
        sb.replace(0, 3, "A"); // Replaces characters from index 0 (inclusive) to 3 (exclusive)
        System.out.println(sb.toString()); // Output: "A quick brown fox jumps over the lazy dog"
        // To replace all occurrences of a substring, you need a loop
        String toFind = "the";
        String toReplace = "a";
        int index;
        while ((index = sb.indexOf(toFind)) != -1) {
            sb.replace(index, index + toFind.length(), toReplace);
        }
        System.out.println(sb.toString());
        // Output: "A quick brown fox jumps over a lazy dog"
    }
}

Summary: Which Method to Use?

Method When to Use Key Feature
replace() To replace all occurrences of a literal string or character. Simple, fast, no regex knowledge needed.
replaceFirst() To replace only the first occurrence of a pattern. Uses regex for flexible pattern matching.
replaceAll() To replace all occurrences of a complex pattern. Uses regex for powerful, pattern-based replacement.
StringBuilder When modifying a string many times in a loop for performance. Mutable, avoids creating many intermediate String objects.
分享:
扫描分享到社交APP
上一篇
下一篇