charAt()
函数在 Java 编程中主要用于从字符串中获取指定索引位置的字符。以下是一些实际应用案例:
public class Main {
public static void main(String[] args) {
String str = "Hello, World!";
// 检查字符串是否以大写字母 'H' 开头
if (str.charAt(0) == 'H') {
System.out.println("The string starts with 'H'");
}
// 检查字符串是否以感叹号 '!' 结尾
int lastIndex = str.length() - 1;
if (str.charAt(lastIndex) == '!') {
System.out.println("The string ends with '!'");
}
}
}
public class Main {
public static void main(String[] args) {
String str = "Programming";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
System.out.println("Character at index " + i + ": " + ch);
}
}
}
public class Main {
public static void main(String[] args) {
String str = "ReverseMe";
StringBuilder reversedStr = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
reversedStr.append(str.charAt(i));
}
System.out.println("Reversed string: " + reversedStr.toString());
}
}
public class Main {
public static void main(String[] args) {
String str = "madam";
boolean isPalindrome = true;
for (int i = 0; i < str.length() / 2; i++) {
if (str.charAt(i) != str.charAt(str.length() - 1 - i)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.println("The string is a palindrome");
} else {
System.out.println("The string is not a palindrome");
}
}
}
这些示例展示了如何在 Java 编程中使用 charAt()
函数。根据实际需求,可以在各种场景中应用这个函数。