案例. 遍历字符串

案例. 遍历字符串

String类的常用方法:
public char charAt(int index);方法,返回指定索引的char值
public int length(); 方法, 返回此字符串长度

import java.util.Scanner;
//键盘输入字符串,在控制台遍历,,例如123,,[1,2,3]
public class printString {
    public static void main(String[] args) {
        //键盘输入字符串
        Scanner s = new Scanner(System.in);
        System.out.println("输入字符串:");
        String str = s.nextLine();
        /*遍历字符串,先要获得字符串的每一个字符
        使用public char charAt(int index);方法,返回指定索引的char值,字符串索引以0开头
        遍历字符串,还要获得字符串长度,
        public int length();  方法, 返回此字符串长度;*/
        System.out.print("[");
        for(int i = 0 ; i < str.length() ; i++){
            if(i==str.length()-1){
                System.out.println(str.charAt(i)+"]");
                break;
            }
            System.out.print(str.charAt(i)+",");
        }
       //数组长度  数组名.length
       //字符串长度  字符串对象.length()

    }
}
posted @ 2023-01-17 15:23  大宝贝94106  阅读(107)  评论(0)    收藏  举报