Phương thức String.endsWith()
public boolean endsWith(String suffix) – trả về true nếu chuỗi kết thúc bằng suffix, ngược lại false. Phân biệt chữ hoa/thường.
Ví dụ
public class EndsWithExample {
public static void main(String[] args) {
String str = "WelcomeToTutorialsPoint";
if (str.endsWith("Point")) {
System.out.println("Kết thúc bằng từ chỉ định!");
} else {
System.out.println("KHÔNG kết thúc bằng từ chỉ định!");
}
// Kiểm tra case-sensitive
System.out.println(str.endsWith("point")); // false
}
}
Kết quả
Kết thúc bằng từ chỉ định!
false
Mẹo: Dùng str.toLowerCase().endsWith(suffix.toLowerCase()) để bỏ qua case. Từ Java 11, có String.endsWith(CharSequence) nạp chồng.