Java API ——Character类
1、Character类的概述
· Character 类在对象中包装一个基本类型 char 的值
· 此外,该类提供了几种方法,以确定字符的类别(小写字母,数字,等等),并将字符从大写转换成小写,反之亦然
2、构造方法
public class CharacterDemo01 { public static void main(String[] args) { //创建对象 Character ch = new Character('a'); System.out.println("ch:"+ch); } }
3、Character类成员方法
· public static boolean isUpperCase(char ch):判断给定的字符是否是大写字符
· public static boolean isLowerCase(char ch):判断给定的字符是否是小写字符
· public static boolean isDigit(char ch):判断给定的字符是否是数字字符
· public static char toUpperCase(char ch):把给定的字符转换为大写字符
· public static char toLowerCase(char ch):把给定的字符转换成小写字符
public class CharacterDemo02 { public static void main(String[] args) { // public static boolean isUpperCase(char ch):判断给定的字符是否是大写字符 System.out.println("isUpperCase:" + Character.isUpperCase('A')); //isUpperCase:true System.out.println("isUpperCase:" + Character.isUpperCase('a')); //isUpperCase:false System.out.println("isUpperCase:" + Character.isUpperCase('0')); //isUpperCase:false System.out.println("-----------------------------------------"); // public static boolean isLowerCase(char ch):判断给定的字符是否是小写字符 System.out.println("isLowerCase:" + Character.isLowerCase('A')); //isLowerCase:false System.out.println("isLowerCase:" + Character.isLowerCase('a')); //isLowerCase:true System.out.println("isLowerCase:" + Character.isLowerCase('0')); //isLowerCase:false System.out.println("-----------------------------------------"); // public static boolean isDigit(char ch):判断给定的字符是否是数字字符 System.out.println("isDigit:" + Character.isDigit('A')); //isDigit:false System.out.println("isDigit:" + Character.isDigit('a')); //isDigit:false System.out.println("isDigit:" + Character.isDigit('0')); //isDigit:true System.out.println("-----------------------------------------"); // public static char toUpperCase(char ch):把给定的字符转换为大写字符 System.out.println("toUpperCase:" + Character.toUpperCase('A')); //toUpperCase:A System.out.println("toUpperCase:" + Character.toUpperCase('a')); //toUpperCase:A System.out.println("-----------------------------------------"); // public static char toLowerCase(char ch):把给定的字符转换为小写字符 System.out.println("toLowerCase:" + Character.toLowerCase('A')); //toLowerCase:a System.out.println("toLowerCase:" + Character.toLowerCase('a')); //toLowerCase:a } }
4、练习题:统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)
public class CharacterDemo03 { public static void main(String[] args) { // 定义三个统计变量。 int bigCount = 0; int smallCount = 0; int numberCount = 0; System.out.println("请输入一个字符串:"); Scanner sc = new Scanner(System.in); String line = sc.nextLine(); char[] ch = line.toCharArray(); for(int i = 0; i < ch.length; i++){ if (Character.isUpperCase(ch[i])) bigCount++; else if(Character.isLowerCase(ch[i])) smallCount++; else if(Character.isDigit(ch[i])) numberCount++; } // 输出结果即可 System.out.println("大写字母:" + bigCount + "个"); System.out.println("小写字母:" + smallCount + "个"); System.out.println("数字字符:" + numberCount + "个"); } }
输出结果:
请输入一个字符串:
hello 123 ABCaa
大写字母:3个
小写字母:7个
数字字符:3个