★String类
一、数组按指定格式输出
数组{1, 2, 3}—>[ world1# world2# world3]输出
public static String fromArrayToString(int[] arr) {
String str = "[";//第一部分
for (int i = 0; i < arr.length; i++) {
if (i < arr.length - 1) {
str += "world" + arr[i] + "#";//第二部分
} else {
str += "world" + arr[i] + "]";//第三部分
}
}
return str;
}
二、统计字符串中各种字符出现的次数
键盘输入字符串,种类:大写字母,小写字母,数字,其他
/*思路:
* 定义四个变量分别代表四种字符出现的次数
* 需要逐个判断字符串中的字符,用到toCharArray()方法
* 遍历字符数组,判断字符种类,对应变量++
* */
public class DemoString {
public static void main(String[] args) {
System.out.println("请输入一个字符串:");
Scanner sca = new Scanner(System.in);
String str = sca.next();
char[] charArray = str.toCharArray();
int countUpper = 0;
int countLower = 0;
int countNumber = 0;
int countother = 0;
for (int i = 0; i < charArray.length; i++) {
char ch = charArray[i];
if (ch > 'A' && ch < 'Z') {
countUpper++;
} else if (ch > 'a' && ch < 'z') {
countLower++;
} else if (ch > '0' && ch < '9') {
countNumber++;
} else {
countother++;
}
}
System.out.println("大写字母有" + countUpper + "个");
System.out.println("小写字母有" + countLower + "个");
System.out.println("数字字符有" + countNumber + "个");
System.out.println("其他字符有" + countother + "个");
}
}