Java String type string to character array, the string gets characters according to the index

1. String to character array

Method: use toCharArray() method

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. Obtain the character value according to the index

str.charAt(index position)

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']++;
        }

Guess you like

Origin blog.csdn.net/qq_63802547/article/details/127797198