天天看點

Java String類型字元串轉字元數組,字元串根據索引獲得字元

1.字元串轉為字元數組

方法:利用toCharArray()方法

char[] arr=str.toCharArray();

import java.util.Scanner;

public class demo_1 {
    public static void main(String[] args) {
        Scanner sc =new Scanner(System.in);
        String str=sc.nextLine();
        char[] arr=str.toCharArray();//字元轉字元數組
        for(int i=0;i<arr.length;i++){
            System.out.println(arr[i]);
        }
    }
}
           

2.根據索引獲得字元值

str.charAt(索引位置)

Scanner sc =new Scanner(System.in);
        String str=sc.nextLine();
        int[] a=new int[26];
        for (int i=0;i<str.length();i++){
            a[str.charAt(i)-'a']++;
        }