String 类包括的方法可用于检查序列的单个字符、比较字符串、搜索字符串、提取子字符串、创建字符串副本并将所有字符全部转换为大写或小写。大小写映射基于 Character 类指定的 Unicode 标准版。
1、检查序列的单个字符:
String c = "abc".substring(2, 3);
System.out.println("c" + c);
String d = "abc".substring(1);
System.out.println("d" + d);
输出结果:c
bc
两个参数的substring方法的意思是开始位置到结束位置。
一个参数的substring方法的意思是从哪个位置开始一直到结束。
2、比较字符:
@Override public boolean equals(Object other) {
if (other == this) {
return true;
}
if (other instanceof String) {
String s = (String)other;
int count = this.count;
if (s.count != count) {
return false;
}
if (hashCode() != s.hashCode()) {
return false;
}
for (int i = 0; i < count; ++i) {
if (charAt(i) != s.charAt(i)) {
return false;
}
}
return true;
} else {
return false;
}
}
这是源码,可以看出有五个比较步骤:
第一个就是如果能直接等(比如int类型的)就返回true。
第二个是判断是否属于String;
第三步判断字符数是否相等;
第四部判断哈希码是否相等;
最后判断每一个字符是否相等;
3、搜索字符串
public int indexOf(String string) {
int start = 0;
int subCount = string.count;
int _count = count;
if (subCount > 0) {
if (subCount > _count) {
return -1;
}
char firstChar = string.charAt(0);
while (true) {
int i = indexOf(firstChar, start);
if (i == -1 || subCount + i > _count) {
return -1; // handles subCount > count || start >= count
}
int o1 = i, o2 = 0;
while (++o2 < subCount && charAt(++o1) == string.charAt(o2)) {
// Intentionally empty
}
if (o2 == subCount) {
return i;
}
start = i + 1;
}
}
return start < _count ? start : _count;
}
public int indexOf(String subString, int start) {
if (start < 0) {
start = 0;
}
int subCount = subString.count;
int _count = count;
if (subCount > 0) {
if (subCount + start > _count) {
return -1;
}
char firstChar = subString.charAt(0);
while (true) {
int i = indexOf(firstChar, start);
if (i == -1 || subCount + i > _count) {
return -1; // handles subCount > count || start >= count
}
int o1 = i, o2 = 0;
while (++o2 < subCount && charAt(++o1) == subString.charAt(o2)) {
// Intentionally empty
}
if (o2 == subCount) {
return i;
}
start = i + 1;
}
}
return start < _count ? start : _count;
}
4、创建字符串
String str = “abc”;
等效于:
char data[] = {‘a’, ‘b’, ‘c’};
String str = new String(data);
所以两种创建方式都可以。
5、endsWith(String suffix)和startsWith(String prefix)
通过后缀和前缀的对比返回布尔类型值。
多数是用于判断文件格式。
6、split(String regex)
通过这个方法拆分字符串,返回数组。
7、valueOf(float f)。
强转用这个方法更加好。静态方法可以直接调用。那个类型类调用就转化为什么类型。
8、转化编码格式。
try {
byte[] b = "cde".getBytes("UTF-8");
String str = new String(b);
}catch(Exception e){
e.toString();
}
9、StringBuffer和StringBuilder之间的区别?
这两个类都能进行字符拼接,我们主要在什么时候用哪个类。
1、首先通过API可以看到StringBuffer,里面方法带synchronized关键字,说明StringBuffer是同步线程操作,换句话说这是线程安全的。
2、通过API看StringBuilder,方法里面不带synchronized关键字,说明StringBuilder并不存在线程问题,
换句话说这是线程不安全的。
3、最后总结,单线程操作,我们可以使用StringBuilder,多线程操作,我们使用StringBuffer。