[JAVA] String常用方法

近期学习java,发现String有很多好用并且常用的方法,这里取几个较为常用的做下笔记!

 1. length()  获得字符串长度

String a = "Hello World!";
System.out.println(a.length());

输出结果为:12

2.  CharAt() 获取一个字符

String a = "Hello World";
System.out.println(a.charAt(1));

输出结果为:e

3. getchars() 获取连续的几个字符,并存在char数组中

String a = "Hello World";
char[] b = new char[10];
a.getChars(0, 5, b, 0);
System.out.println(b);

截取a的从0开始的5个字符,依次存在b数组。输出结果为:Hello

4. toCharArray()将字符串变成一个字符数组

String a = "Hello World";
char[]b = a.toCharArray();
System.out.println(b);  

输出结果为字符数组b

5. substring() 截取字符串

String a = "Hello World";
System.out.print(a.substring(0, 5));
System.out.println(" "+a.substring(6));

输出结果为:Hello world

6. indexOf() 和 lastIndexOf() 前者是查找字符或字符串第一次出现的地方,后者是查找字符或字符串最后一次出现的地方

String a = "Hello World";
System.out.print(a.indexOf("o"));
System.out.println(" "+a.lastIndexOf("o"));

输出结果为:4 7

猜你喜欢

转载自www.cnblogs.com/lvcoding/p/9098002.html