Giới thiệu
Trong bài viết này, chúng ta sẽ tìm hiểu cách lấy một ký tự từ chuỗi cho trước. char là kiểu dữ liệu chứa chữ cái, số hoặc ký tự đặc biệt. Chuỗi chứa một hoặc nhiều ký tự, được đặt trong dấu ngoặc kép (" ").
Minh họa
Đầu vào:
Input string: Java Programming Index: 11
Đầu ra mong muốn:
Result: m
Thuật toán
- Bắt đầu
- Khai báo: chuỗi
input_string, ký tựresultant_character - Khởi tạo giá trị
- Dùng hàm
string.charAt()để lấy ký tự tại vị trí chỉ định, lưu vàoresultant_character - Hiển thị kết quả
- Kết thúc
Ví dụ 1: Triển khai trong hàm main
public class CharacterAndString {
public static void main(String[] args) {
String string = "Java Programming";
System.out.println("The string is defined as " + string);
int index = 11;
char resultant_character = string.charAt(index);
System.out.println("\nA character from the string :" + string + " at index " + index + " is: " + resultant_character);
}
}
Đầu ra
The string is defined as Java Programming A character from the string :Java Programming at index 11 is: m
Ví dụ 2: Tách hàm static
public class CharacterAndString {
public static char get_chararacter(String string, int index) {
return string.charAt(index);
}
public static void main(String[] args) {
String string = "Java Programming";
System.out.println("The string is defined as " + string);
int index = 11;
char resultant_character = get_chararacter(string, index);
System.out.println("\nA character from the string :" + string + " at index " + index + " is: " + resultant_character);
}
}
Đầu ra
The string is defined as Java Programming A character from the string :Java Programming at index 11 is: m