需求:键盘录入一个字符串,使用程序实现再控制台遍历该字符串
public char charAt(int index)根据索引返回字符
public int length();返回此字符串的长度
数组的长度arr.length
字符串长度: chs.length()
//键盘录入一个字符串 Scanner sc = new Scanner(System.in); System.out.println("请输入一个字符串"); String str = sc.next(); //进行遍历 for (int i = 0; i < str.length(); i++) { //依次获取每一个索引 char c = str.charAt(i); System.out.println(c); }
统计字符次数
public class Demo6 { public static void main(String[] args) { //键盘录入一个字符串 Scanner sc = new Scanner(System.in); String str = sc.next(); //统计大小写字符,数字字符出现的次数! //计数器思想 //定义三个计数器 int bigCount = 0; int smallCount = 0; int numberCount = 0; //遍历数组 for (int i = 0; i < str.length(); i++) { //依次获取每一个字符对应的索引 char c = str.charAt(i); System.out.println(c); if (c >= 'a' && c <= 'z') { smallCount++; } else if (c >= 'A' && c <= 'Z') { bigCount++; } else if (c >= '0' && c <= '9') { numberCount++; } } System.out.println("大写的" + bigCount); System.out.println("小写的" + smallCount); System.out.println("数字有" + numberCount); } }
拼接字符串
定义一个方法,把int数组中的数据按照指定的格式拼接成一个字符串返回,调用该方法,并在控制台输出结果
例如:数组为int[] arr=[1,2,3]
输出[1,2,3]
public class DEmo7 { public static void main(String[] args) { int[] arr = {1, 2, 3}; String str = arrToString(arr); System.out.println(str); } //遍历数组拼接字符串 //数组 //需要返回值,返回拼接后的字符串 public static String arrToString(int[] arr) { if (arr == null) { return ""; } if (arr.length == 0) { return "[]"; } String result = "["; //代码执行到这里,说明数组不空 长度不为0 for (int i = 0; i < arr.length; i++) { //i索引 arr[i]元素 if (i == arr.length - 1) { result = result + arr[i]; } else { result = result + arr[i] + ", "; } } result = result + "]"; return result; } }
字符串的反转
public class Demo8 { public static void main(String[] args) { String str = reverser("abc"); System.out.println(str); } //实现字符反转 //字符串 //返回字符串 public static String reverser(String str) { //abc->cba String result = ""; //arr.forr,可以倒着遍历 for (int i = str.length() - 1; i >= 0; i--) { //依次表示字符串每一个索引 char c = str.charAt(i); // System.out.println(c); result = result + c; } return result; } }