Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Các phương thức replace(), replaceFirst(), replaceAll() của String trong Java

1. replace(char oldChar, char newChar) / replace(CharSequence target, CharSequence replacement)

  • Thay thế TẤT CẢ lần xuất hiện của ký tự/chuỗi con.
  • Không dùng regex (plain text).
  • Trả về String mới (String immutable).
String s = "Hello World";
s.replace('l', '#');     // "He##o Wor#d"
s.replace("World", "Java"); // "Hello Java"

2. replaceAll(String regex, String replacement)

  • Thay thế TẤT CẢ khớp với regex.
  • Hỗ trợ regex đầy đủ.
String s = "Hello World";
s.replaceAll("\\s+", "-");   // "Hello-World" (space -> dash)
s.replaceAll("(?i)hello", "Hi"); // "Hi World" (case-insensitive)

3. replaceFirst(String regex, String replacement)

  • Chỉ thay thế LẦN ĐẦU TIÊN khớp regex.
String s = "Hello Hello World";
s.replaceFirst("Hello", "Hi"); // "Hi Hello World"

So sánh nhanh

MethodThay thếRegex?Số lần
replace(char, char)Ký tựKhôngTất cả
replace(CharSequence, CharSequence)ChuỗiKhôngTất cả
replaceAll(regex, repl)RegexCóTất cả
replaceFirst(regex, repl)RegexCóChỉ lần 1

Ví dụ thực tế từ file

String content = "Tutorialspoint provides tutorials. Tutorialspoint is great.";

// replace - plain text
content.replace("Tutorialspoint", "TP"); 
// "TP provides tutorials. TP is great."

// replaceAll - regex word boundary
content.replaceAll("\\bTutorialspoint\\b", "TP");
// "TP provides tutorials. TP is great."

// replaceFirst - chỉ lần đầu
content.replaceFirst("Tutorialspoint", "TP");
// "TP provides tutorials. Tutorialspoint is great."

Lưu ý hiệu suất

  • replace(CharSequence, CharSequence) (Java 9+) tối ưu nội bộ, nhanh hơn replaceAll cho plain text.
  • replaceAll compile regex mỗi lần gọi. Nếu dùng lặp, compile sẵn Pattern.
  • Tất cả đều case-sensitive mặc định. Dùng (?i) trong regex cho case-insensitive.