Trong bài viết này, chúng ta sẽ hiểu cách kiểm tra String rỗng (Empty) hoặc Null. String là kiểu dữ liệu chứa một hoặc nhiều ký tự và được bao quanh bởi dấu ngoặc kép (" ").
Minh họa dưới đây:
Giả sử đầu vào là:
Input string: null
Đầu ra mong muốn:
The string is a null string
Thuật toán
Bước 1 - BẮT ĐẦU Bước 2 - Khai báo string input_string Bước 3 - Định nghĩa giá trị Bước 4 - Dùng if kiểm tra input_string == null. Nếu true, string là null, else không null Bước 5 - Hiển thị kết quả Bước 6 - DỪNG
Ví dụ 1
Gom thao tác dưới 'main'.
public class Demo {
public static void main(String[] args) {
String input_string = null;
System.out.println("The string is defined as: " + input_string);
if (input_string == null) {
System.out.println("\nThe string is a null string");
} else if(input_string.isEmpty()){
System.out.println("\nThe string is an empty string");
} else {
System.out.println("\nThe string is neither empty nor null string");
}
}
}
Kết quả
The string is defined as: null The string is a null string
Ví dụ 2
Đóng gói thao tác vào hàm thể hiện lập trình hướng đối tượng.
public class Demo {
static void isNullEmpty(String input_string) {
if (input_string == null) {
System.out.println("\nThe string is a null string");
} else if(input_string.isEmpty()){
System.out.println("\nThe string is an empty string");
} else {
System.out.println("\nThe string is neither empty nor null string");
}
}
public static void main(String[] args) {
String input_string = null;
System.out.println("The string is defined as: " + input_string);
isNullEmpty(input_string);
}
}
Kết quả
The string is defined as: null The string is a null string