参考资料
[1]. 疯狂Java讲义(第三版) 李刚
概述
String类是不可变类
String
获取指定位置的字符串
String s = new String("www.qunar.com");
System.out.println(s.charAt(4));
compareTo,比较字符串
比较两个字符串的大小,如果两个字符串的字符序列相等,则返回0;不相等时,从两个字符串第0个字符开始比较,返回第一个不相等的字符差。另一种情况,较长字符串的前面部分恰巧是较短的字符串,则返回它们的长度差。
String s1 = new String("abcdefghijklmn");
String s2 = new String("abcdefghij");
String s3 = new String("abcdefghijklmn");
// 输出4,s1与s2相比
System.out.println(s1.compareTo(s2));
// 输出0,s1与s3相比
System.out.println(s1.compareTo(s3));
endsWith,比较字符串尾部
String s1 = "abcdef.com";
String s2 = ".com";
// 输出true
System.out.println(s1.endsWith(s2));
getChars
endsWith方法将字符串中从srcBegin开始,到srcEnd结束的字符复制到dst字符数组中,其中dstBegin为目标字符数组的起始复制位置。
即使用String类型从char类型变量中抽取一些字符串后,替换。
char[] s1 = {'I', ' ', 'l', 'o', 'v', 'e', ' ', 'j', 'a', 'v', 'a'};
String s2 = new String("ejb");
s2.getChars(0, 3, s1, 7);
System.out.println(s1);
indexOf,找位置
String s = "www.baidu.com";
String ss = "du";
System.out.println(s.indexOf('b'));
System.out.println(s.indexOf('b',2));
System.out.println(s.indexOf(ss));
startsWith,是否是以某个开头
String s = "www.fkit.org";
String ss = "www";
String sss = "fkit";
// true
System.out.println(s.startsWith(ss));
// true
System.out.println(s.startsWith(sss,4));
将字符串转换成大写和小写
String s = "www.fkit.org";
// 转换成大写
System.out.println(s.toUpperCase());
// 转换成小写
System.out.println(s.toLowerCase());