一、判断功能
String s="";//字符串为空
String s=null;//字符串对象为空
String s1="helloworld";
String s2="helloworld";
String s3="Helloworld";
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equalsIgnoreCase(s2));
System.out.println(s1.equalsIgnoreCase(s3));
System.out.println(s1.contains("hello"));
System.out.println(s1.contains("wd"));
System.out.println(s1.startsWith("h"));
System.out.println(s1.startsWith("hello"));
System.out.println(s1.endsWith("d"));
System.out.println(s1.endsWith("hello"));
二、获取功能
String s="helloworld";
System.out.println(s.length());//10
System.out.println(s.charAt(7));//r
System.out.println(s.indexOf('h'));//0
System.out.println(s.indexOf("owo"));//4
System.out.println(s.indexOf('l',4));//8
System.out.println(s.indexOf("ow",2));//4
System.out.println(s.substring(4));//oworld
System.out.println(s.substring(3, 7));//lowo
遍历字符串的每一个字符
String s="helloworld";
for(int i=0;i<s.length();i++){
System.out.println(s.charAt(i));
}
}
结果:
h
e
l
l
o
w
o
r
l
d
三、转换功能
String s="helloworld";
byte[] bs=s.getBytes();
//将字符串转换为字节数组
for(int i=0;i<bs.length;i++){
System.out.println(bs[i]);
}
/*104
101
108
108
111
119
111
114
108
100*/
//将字符串转换为字节数组
char[] ch=s.toCharArray();
for(int i=0;i<ch.length;i++){
System.out.println(ch[i]);
}
/*h
e
l
l
o
w
o
r
l
d*/
//将字符数组转换为字符串
String str=String.valueOf(ch);
System.out.println(str);//helloworld
//将int型转换为字符串类型
int i=100;
String ss=String.valueOf(i);
System.out.println(ss);//100,这里的100已经是String型了
//将字符串转换为小写
String s1="HelloWorld";
System.out.println(s1.toLowerCase());//helloworld
System.out.println(s1.toUpperCase());//HELLOWORLD
//字符串的连接
String s2="hello";
String s3="world";
String s4=s2.concat(s3);
//等同于String s4=s2+s3;
System.out.println(s4);
四、其他功能
String s="helloworld";
String s1=s.replace('l','k');
String s2=s.replace("owo", "xxxx");
System.out.println(s1);//hekkoworkd
System.out.println(s2);//hellxxxxrld
//去两边的空格
String s3=" ksflk ";
String s4=s3.trim();
System.out.println(s4+"------");//ksflk------
//字符串比较
String s5="hello";
String s6="hello";
String s7="abc";
String s8="xyz";
System.out.println(s5.compareTo(s6));//0
System.out.println(s5.compareTo(s7));//7 字符串比较,首先比较第一个字符,如果相同,再比较下一个,如果不同,就用前面那个值的ascall码值减去后面的,依次循环下去
System.out.println(s5.compareTo(s8));//