目录
5:字符串分割split(String sign,int limit)
String类字符串的声明和创建:
String s=new String(可为String类 or char[]数组 or 空);
String s="hello world";//直接声明内容创建
一:连接多个字符串和其它数据类型
String s1=new String("hello ");
String s2=new String("world");
String s3="!";
int a=33;
System.out.println(s1+s2+s3);
System.out.println(s1+s2+s3+a);//类型不同时自动转化为String
输出结果:hello world!
hello world!33
二:获取字符串长度,查询子串位置,根据脚标检索字符
String s=new String("hello");
String t="l";
System.out.println(s.length());//获取字符串长度
//从前往后检索子串t的首字符位置,若没有查找到返回-1:
System.out.println(s.indexOf(t));
//从后往前检索子串t的首字符位置,若没有查找到返回-1:
System.out.println(s.lastIndexOf(t));
System.out.println(s.charAt(4));//检索出脚标为4的位置处的字符
输出结果:5
2
3
o
三:字符串操作
1:字符串截取,substring()操作可用于截取子字符串,其方法被重载为两种,代码示例如下
//s.substring(int beginIndex) 从当前脚标为beginIndex的位置开始截取到字符串结束
//s.substring(int beginIndex,int endIndex) 从脚标beginIndex截取到脚标endIndex处截止,左开右闭
String s="甲乙丙丁戊己庚辛壬癸";
String t1=s.substring(4);//从脚标4的位置开始截取
String t2=s.substring(3,6);
System.out.println(t1);
System.out.println(t2);
输出结果:戊己庚辛壬癸
丁戊己
2:除去前后空格,trim()操作可去除前导空格和末尾空格
String s=" 甲乙 丙丁 ";//s长度为7
System.out.println(s.length());
s=s.trim();
System.out.printf("%s %d",s,s.length());
输出结果:7
5 甲乙 丙丁
3:判断两串是否相等,equals()提供了判断两串是否相等的方法
String s="甲乙 丙丁";
String t="甲乙丙丁";
String t1="甲乙丙丁";
System.out.println(t.equals(t1));
System.out.println(t.equals(s));
输出结果:true
false
4:字母大小写转换,toLowerCase()提供将全部英文字母转化为小写,toUpperCase()提供转换成小写
String s="HeLlo WoRlD";//s长度为7
System.out.println(s.toLowerCase());
System.out.println(s.toUpperCase());
输出结果:hello world
HELLO WORLD
5:字符串分割,split(String sign,int limit)提供根据给定的sign进行分串,并且能限定分割limit个字符串(注意不是limit次),String sign中可使用正则表达式。
String s="aaebbbecccc";//s长度为7
String[] t=s.split("e",2);
for(String a:t) System.out.println(a);
输出结果:aa
bbecccc