Java Sting 常见方法

toUpperCase() 字符串转大写
toLowerCase() 字符串转小写

String str="hello world!";
System.out.println(str.toUpperCase());
System.out.println(str.toLowerCase());

trim() 去掉首尾空格

String str="  hello world   ";
System.out.println(str.trim());

只去掉首尾空格,不影响中间的。

indexOf() 返回指定字符或字符串在某一个字符串中第一次出现的位置,若不存在返回 -1 。

String str="hello world";
System.out.println(str.indexOf('l'));
//输出l第一次出现的位置 2

lastIndexOf() 返回最后一次出现的位置,其他的属性跟indexOf()一样。

System.out.println(str.indexOf('l'));
//输出9

indexOf 和lastIndexOf 的返回值都是int类型。

subString() 截取字符串
截取start位置到end位置的字符串,取不到end (因为 [ ) 半闭半开区间)

String str="hello world";
System.out.println(subString(1,3));
//输出el
//函数原型 subString(start,end)
//如果参数是一个,那么这位置到字符串结束

split() 按指定字符或字符串拆分字符串,返回值为数组。

String str="12-345-678";
String[] str2=str.split('-');
System.out.println(str2[0]); //12
System.out.println(str2[1]); //345
System.out.println(str2[2]); //678

猜你喜欢

转载自blog.csdn.net/weixin_45886555/article/details/105132276