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 中的多种应用场景。你可以根据需要调整代码以满足你的具体需求。