charAt() 是 Java 中的一個字符串方法,它用于返回指定索引處的字符。這個方法在處理字符串時非常有用,因為它允許你訪問和操作字符串中的單個字符。以下是一些具體的應用場景:
String str = "Hello, World!";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
System.out.println("Character at index " + i + " is: " + ch);
}
String str = "Hello, World!";
int index = str.indexOf('W');
if (index != -1) {
System.out.println("Character 'W' found at index: " + index);
} else {
System.out.println("Character 'W' not found");
}
String str = "Hello, World!";
int startIndex = 0;
int endIndex = 5;
String subStr = str.substring(startIndex, endIndex);
System.out.println("Substring from index " + startIndex + " to " + endIndex + " is: " + subStr);
String str = "Hello, World!";
String newStr = str.replace('World', 'Java');
System.out.println("Original string: " + str);
System.out.println("New string: " + newStr);
String str = "Hello, World!";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (Character.isLetter(ch)) {
System.out.println("Character at index " + i + " is a letter: " + ch);
} else if (Character.isDigit(ch)) {
System.out.println("Character at index " + i + " is a digit: " + ch);
} else {
System.out.println("Character at index " + i + " is a special character: " + ch);
}
}
這些示例展示了 charAt() 方法在 Java 中的多種應用場景。你可以根據需要調整代碼以滿足你的具體需求。