溫馨提示×

charat函數(shù)在Java編程中的實際應(yīng)用案例有哪些

小樊
82
2024-09-07 12:25:44
欄目: 編程語言

charAt() 函數(shù)在 Java 編程中主要用于從字符串中獲取指定索引位置的字符。以下是一些實際應(yīng)用案例:

  1. 檢查字符串是否以特定字符開頭或結(jié)尾
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'");
        }
        
        // 檢查字符串是否以感嘆號 '!' 結(jié)尾
        int lastIndex = str.length() - 1;
        if (str.charAt(lastIndex) == '!') {
            System.out.println("The string ends with '!'");
        }
    }
}
  1. 遍歷字符串中的所有字符
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);
        }
    }
}
  1. 反轉(zhuǎn)字符串
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());
    }
}
  1. 檢查字符串是否為回文(正序和倒序讀都一樣的字符串):
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() 函數(shù)。根據(jù)實際需求,可以在各種場景中應(yīng)用這個函數(shù)。

0