下面来看String类的一般方法
public int length() {
return value.length;
}
这是返回String长度的方法,也就是char数组value的长度
public boolean isEmpty() {
return value.length == 0;
}
这是判断String是否是无内容的字符串的方法,也就是判断char数组value的长度是否为0
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
这是返回String对象中指定字符的方法,也就是返回char数组value的指定元素
public int codePointAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return Character.codePointAtImpl(value, index, value.length);
}
这个方法返回的是指定索引的代码点。
先来普及一下代码点和代码单元的概念。代码点就是一个Unicode字符,代码单元是代码点的集合。Unicode(统一码、万国码、单一码)是一种在计算机上使用的字符编码。它为每种语言中的每个字符设定了统一并且唯一的二进制编码,以满足跨语言、跨平台进行文本转换、处理的要求,Unicode字符从0000到FFFF,以16进制数字为基本单位。
这个方法就是返回String对象指定索引上的Unicode字符对应的十进制数字。举个例子:
String test="s";
for(int i=0;i<test.length();i++){
System.out.println(test.codePointAt(i));
}
这段程序返回115,把115转换成十六进制是73,字母s的十六进制Unicode字符为0073,明白了吧?
这个方法的底层调用了Character类的方法,比较有意思,在这里为了节省篇幅,暂时不谈,我在学习Character类时会研究相关方法的实现。
public int codePointBefore(int index) {
int i = index - 1;
if ((i < 0) || (i >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return Character.codePointBeforeImpl(value, index, 0);
}
这个方法是返回指定索引前一个索引的代码点,如果输入0则会报异常。
public int codePointCount(int beginIndex, int endIndex) {
if (beginIndex < 0 || endIndex > value.length || beginIndex > endIndex) {
throw new IndexOutOfBoundsException();
}
return Character.codePointCountImpl(value, beginIndex, endIndex - beginIndex);
}
这个方法返回的是指定索引区间内的代码点长度,看似很简单,实际底层隐藏着一些深层的东西,代码点长度不等于字符个数,这个以后再说,先买个关子:
String str="\uDBFF\uDC01\uDC02\uDC03";
System.out.println(str.length());
System.out.println(str.codePointCount(0, 4));
这段代码两个打印结果是不一样的。
public int offsetByCodePoints(int index, int codePointOffset) {
if (index < 0 || index > value.length) {
throw new IndexOutOfBoundsException();
}
return Character.offsetByCodePointsImpl(value, 0, value.length,
index, codePointOffset);
}
这个方法比较有意思,是返回从String对象指定索引开始,到另一个指定索引结束的区间内的代码点长度,这个也会在以后说明,还是先卖个关子:
String str1="\uDBFE\uDBFF\uDC02\uDC03";
String str2="zbcc";
System.out.println(str1.offsetByCodePoints(0, 2));
System.out.println(str2.offsetByCodePoints(0, 2));
这段代码两个打印结果也是不一样的。