API String trong Java
String là một trong những lớp được sử dụng phổ biến nhất trong Java. Nó cung cấp nhiều phương thức hữu ích để thao tác với chuỗi ký tự.
1. Tạo String
Sử Dụng Literal
String str1 = "Hello World";
String str2 = "Hello World"; // Sử dụng cùng object trong String Pool
Sử Dụng Constructor
String str1 = new String("Hello World");
String str2 = new String("Hello World"); // Tạo object mới
Từ Mảng Ký Tự
char[] chars = {'H', 'e', 'l', 'l', 'o'};
String str = new String(chars);
Từ StringBuilder
StringBuilder sb = new StringBuilder("Hello");
String str = sb.toString();
2. String Pool
Khái Niệm
String s1 = "Hello"; // Tạo trong String Pool
String s2 = "Hello"; // Sử dụng lại từ String Pool
String s3 = new String("Hello"); // Tạo object mới
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
Intern
String s1 = "Hello";
String s2 = new String("Hello").intern(); // Đưa vào String Pool
System.out.println(s1 == s2); // true
3. Phương Thức Cơ Bản
Độ Dài và Kiểm Tra Rỗng
String str = "Hello";
int length = str.length(); // 5
boolean isEmpty = str.isEmpty(); // false
boolean isBlank = str.isBlank(); // false
Truy Cập Ký Tự
String str = "Hello";
char firstChar = str.charAt(0); // 'H'
int index = str.indexOf('l'); // 2
int lastIndex = str.lastIndexOf('l'); // 3
Cắt Chuỗi
String str = "Hello World";
String sub1 = str.substring(0, 5); // "Hello"
String sub2 = str.substring(6); // "World"
Thay Thế
String str = "Hello World";
String replaced = str.replace('l', 'L'); // "HeLLo WorLd"
String replacedAll = str.replaceAll("l", "L"); // "HeLLo WorLd"
4. So Sánh Chuỗi
So Sánh Cơ Bản
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
boolean equals1 = s1.equals(s2); // true
boolean equals2 = s1.equals(s3); // true
boolean equals3 = s1 == s2; // true
boolean equals4 = s1 == s3; // false
So Sánh Không Phân Biệt Chữ Hoa/Thường
String s1 = "Hello";
String s2 = "hello";
boolean equalsIgnoreCase = s1.equalsIgnoreCase(s2); // true
So Sánh Thứ Tự
String s1 = "Apple";
String s2 = "Banana";
int compare = s1.compareTo(s2); // < 0
int compareIgnoreCase = s1.compareToIgnoreCase(s2); // < 0
5. Chuyển Đổi Kiểu Dữ Liệu
Từ String sang Các Kiểu Khác
String number = "123";
int intValue = Integer.parseInt(number);
double doubleValue = Double.parseDouble("123.45");
boolean boolValue = Boolean.parseBoolean("true");
Từ Các Kiểu Khác sang String
int number = 123;
String str1 = String.valueOf(number);
String str2 = Integer.toString(number);
String str3 = "" + number; // Không khuyến khích
6. Xử Lý Chuỗi Nâng Cao
Tách Chuỗi
String str = "Hello,World,Java";
String[] parts = str.split(","); // ["Hello", "World", "Java"]
String[] parts2 = str.split(",", 2); // ["Hello", "World,Java"]
Nối Chuỗi
String s1 = "Hello";
String s2 = "World";
String result = s1.concat(" ").concat(s2); // "Hello World"
String result2 = s1 + " " + s2; // "Hello World"
Định Dạng Chuỗi
String name = "John";
int age = 30;
String formatted = String.format("Name: %s, Age: %d", name, age);
7. Ví Dụ Thực Tế
Xử Lý Email
public class EmailValidator {
public static boolean isValidEmail(String email) {
if (email == null || email.isEmpty()) {
return false;
}
// Kiểm tra định dạng cơ bản
if (!email.contains("@") || !email.contains(".")) {
return false;
}
// Kiểm tra ký tự đặc biệt
String specialChars = "[^a-zA-Z0-9@._-]";
if (email.matches(specialChars)) {
return false;
}
return true;
}
}
Xử Lý Mật Khẩu
public class PasswordValidator {
public static boolean isValidPassword(String password) {
if (password == null || password.length() < 8) {
return false;
}
// Kiểm tra chữ hoa
boolean hasUpperCase = password.matches(".*[A-Z].*");
// Kiểm tra chữ thường
boolean hasLowerCase = password.matches(".*[a-z].*");
// Kiểm tra số
boolean hasNumber = password.matches(".*\\d.*");
// Kiểm tra ký tự đặc biệt
boolean hasSpecial = password.matches(".*[!@#$%^&*()].*");
return hasUpperCase && hasLowerCase && hasNumber && hasSpecial;
}
}
8. Best Practices
-
Sử Dụng StringBuilder cho Chuỗi Động
// Không nên
String result = "";
for (int i = 0; i < 1000; i++) {
result += "a";
}
// Nên
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append("a");
}
String result = sb.toString(); -
So Sánh An Toàn
// Không nên
if (str == "Hello") { }
// Nên
if ("Hello".equals(str)) { } -
Xử Lý Null
// Không nên
String result = str.toUpperCase();
// Nên
String result = str != null ? str.toUpperCase() : null;
9. Lỗi Thường Gặp
-
Quên Kiểm Tra Null
// Lỗi
String str = null;
int length = str.length(); // NullPointerException
// Đúng
if (str != null) {
int length = str.length();
} -
So Sánh Sai Cách
// Lỗi
if (str == "Hello") { }
// Đúng
if ("Hello".equals(str)) { } -
Vấn Đề Encoding
// Lỗi
String str = new String(bytes); // Quên encoding
// Đúng
String str = new String(bytes, StandardCharsets.UTF_8);