Java学习笔记-5-字符串

String

统计字符串个数:

 1 public static void main(String[] args) {
 2         //键盘录入一个字符串数据
 3         Scanner sc = new Scanner(System.in);
 4         System.out.println("请输入一个字符串数据:");
 5         String s = sc.nextLine();
 6         //定义四个统计变量,初始化值都是0
 7         int bigCount = 0;
 8         int smallCount = 0;
 9         int numberCount = 0;
10         int orther = 0;
11         //遍历字符串,得到每一个字符
12         for (int x = 0; x < s.length(); x++) {
13             char ch = s.charAt(x);
14             //拿字符进行判断
15             if (ch >= 'A' && ch <= 'Z') {
16                 bigCount++;
17             } else if (ch >= 'a' && ch <= 'z') {
18                 smallCount++;
19             } else if (ch >= '0' && ch <= '9') {
20                 numberCount++;
21             } else {
22                 orther++;
23             }
24         }
25         //输出结果
26         System.out.println("大写字符:" + bigCount + "个");
27         System.out.println("小写字符:" + smallCount + "个");
28         System.out.println("数字字符:" + numberCount + "个");
29         System.out.println("其他字符:" + orther + "个");
30     }

结果:

请输入一个字符串数据:
CM&plb&123
大写字符:2个
小写字符:3个
数字字符:3个
其他字符:2个

常用API

isEmpty()           

判断是否为0

equals()  

比较  

equalsIgnoreCase()  

比较不区分大小写

length()              

获取长度      

Concat()              

连接/拼接     

charAt()    

通过索引得到字符

indexOf(e)    

eString里面第一个出现的索引

lastIndexOf(e)    

最后一个出现的索引     

substring(a)(a,b)

a开始截取,ab,不包括b

toCharArray()       

转换成字符数组   

getBytes()          

转换成字节数组   

replace(“a”,”b”)        

a替换成b     

split()             

分割

trim()

去掉空格

URLEncoder.encode(str,”UTF-8”)

进行URLEncoder编码

StringBuilder

常用API

append();

添加任意类型数据的字符串形式,并返回当前对象自身。

toString();     

StringBuilder对象转换为String对象。

reverse();

StringBuilder对象里面的内容反转

猜你喜欢

转载自www.cnblogs.com/cmmplb/p/11735693.html