JAVA中遍历字符串的两种方法
JAVA中遍历字符串的两种方法
第一种
直接遍历
import java.util.Scanner; public class Demo3 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("请输入:"); String s = sc.nextLine(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); System.out.println(c); } } }
第二种
转换成数组后遍历数组
import java.util.Scanner; public class Demo4 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入:"); String s = sc.nextLine(); // 将字符串拆分为字符数组 char[] chars = s.toCharArray(); // 遍历字符数组 for (int i = 0; i < chars.length; i++) { System.out.println(chars[i]); } } }