1、遍历字符串
键盘录入字符串,使用程序在控制台遍历该字符串
扩展:字符串的长度:字符串对象.length();
public static void main(String[] args) {
//键盘录入字符串
Scanner sc = new Scanner(System.in);
System.out.println("请输入字符串:");
String str = sc.next();
//2、字符串进行遍历 str.length().fori
for (int i = 0; i < str.length(); i++) {
//依次表示字符串的索引
char c = str.charAt(i);//ctrl+alt+v自动生成左边
System.out.print(c + " ");
}
}
2、统计字符的个数
键盘录入字符串的,统计该字符串中大写字母字符,小写字母字符,数字字符出现的次数
public class StringDemo6 {
public static void main(String[] args) {
//键盘录入字符串的,统计该字符串中大写字母字符,小写字母字符,数字字符出现的次数
//1、键盘录入字符串
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String str = sc.next();
//2、统计,计数器思想,定义三个计数器,
int bigCount = 0;
int smallCount = 0;
int numberCount = 0;
int otnerCount = 0;
//3、得到每一个字符并判断
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 'a' && c <= 'z') {
//char类型的变量在参与运算的时候自动将类型提升为int,查询ascii
smallCount++;
} else if (c >= 'A' && c <= 'Z') {
bigCount++;
} else if (c >= '0' && c <= '9') {
numberCount++;
} else {
otnerCount++;
}
}
System.out.println(bigCount);
System.out.println(smallCount);
System.out.println(numberCount);
System.out.println(otnerCount);
}
3、字符串拼接
定义一个方法,把int数组中的数据按照指定的格式拼接为字符串,返回调用该方法,并在控制台打印输出。
例如:int[] arr={1,2,3}; 打印输出的结果为:[1,2,3]
package Test;
public class SreingDemo7 {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
String str = arrToString(arr);
System.out.println(str);
}
//定义一个方法,把int数组中的数据按照指定的格式拼接为字符串,返回调用该方法,并在控制台打印输出。
/**
* 分析:
* 1、遍历数组并把数组拼接为一个字符串
* 2、先给数组(参数)
* 3、再返回一个拼接后的字符串
*
* @param arr
* @return
*/
public static String arrToString(int[] arr) {
if (arr == null) {
return "";
}
if (arr.length == 0) {
return "[]";
}
String result = "[";
//在这一行表示数组是有内容的数组
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] + ", ";
}
}
return result + "]";
}
}