Java学习笔记97——String类的转换案例
案例1
1:遍历获取字符串中的每一个字符 2:统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)
public class StringDemo9 {
public static void main(String[] args) {
String s = "hadoopjavaMySQL12138";
//遍历获取字符串中的每一个字符
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
System.out.print(chars[i]);
}
System.out.println();
//统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)
//定义三个变量统计三个结果
int bigCount = 0;
int smallCount = 0;
int numberCount = 0;
//遍历字符数组,得到每一个字符
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (c >= 'A' && c <= 'Z') {
bigCount++;
} else if (c >= 'a' && c <= 'z') {
smallCount++;
} else if (c >= '0' && c <= '9') {
numberCount++;
}
}
//输出结果
System.out.println("大写字符的个数为:" + bigCount);
System.out.println("小写字符的个数为:" + smallCount);
System.out.println("数字字符的个数为:" + numberCount);
}
}
案例2
需求:将一个字符串的首字母转成大写,其余字母转成小写
举例:"hADoopJava" ---> "Hadoopjava"
分析: 1、全部转成小写 2、获取第一个字符,转成大写
public class StringDemo10 {
public static void main(String[] args) {
String s = "hADoopJava";
//将字符串中每一个字符转小写
String s1 = s.toLowerCase();
//获取第一个字符
String s2 = s1.substring(0, 1);
//将第一个字符转大写
String s3 = s2.toUpperCase();
//获取除第一个字符以外的字符串
String s4 = s1.substring(1);
//将转大写的字符与后面所有小写的进行拼接
String res = s3.concat(s4);
System.out.println(res);
System.out.println("****链式编程*********************");
String res2 = s.substring(0, 1)
.toUpperCase()
.concat(s.substring(1).toLowerCase());
System.out.println(res2);
}
}

浙公网安备 33010602011771号