本篇将根据String.java进行记录String中需要注意的方法、变量。
String基本内容
属性
String类中存储一个声明为value的char数组,int类型的hash,long类型的序列化ID
1 | /** The value is used for character storage. */ |
构造函数
无参构造函数,实例化一个空字符串。
可以直接传入StringBuffer进行实例化String对象。
String.charAt(int index)
String的length(),isEmpty()函数比较基础,就是对char数据的判断。
charAt() 会对index进行判断,如果超出了value的下标范围,就会抛出异常。
1 | public char charAt(int index) { |
String.codePointAt(int index)
返回Unicode编码数
1 | String s = "123"; |
codePointBefore(int index)
返回前一个数的unicode编码。
codePointCount(int beginIndex, int endIndex)
返回开始至末尾的码点数。
String.getChars&getBytes
String.getChars()
1 | /** |
从String的dstBegin到dstBegin + (srcEnd-srcBegin) - 1位置复制到dst数组中。
1 | getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) |
从String的dstBegin开始的位置复制到dst数组中。
1 | getChars(char dst[], int dstBegin) |
String.getBytes()
返回字符对应的字节,默认采用UTF-8
1 | /** |
String.equals()
重写了Object的方法,通过对每个字符进行比较。
contentEquals(StringBuffer): 直接与StringBuffer进行比较。equalsIgnoreCase(String anotherString)忽略大小写比较。
String.hashCode()
重写了Object的方法。
String hash值计算:h = 31 * h + val[i];
至每个位的hash值为== *{31 * 上一个位的hash + 当前的ASCII值}*
1 | public int hashCode() { |
参考:
String.compareTo()
1 | /* |
返回字典序的比较。
String.regionMatches()
1 | /* |
regionMatches() 方法用于比较两个字符串在一个区域内是否相等。
String.startsWith()
1 | public boolean startsWith(String prefix, int toffset) |
比较从toffset起,是否比配前缀prefix
endsWith(String suffix)
比较后缀。
String.indexOf()
所有方法都是获得某个字符或者字符串对应的第一个或者最后一个下标。
共有14个相关方法。
1 | public int indexOf(String str) |
String.substring()
public String substring(int beginIndex, int endIndex)public String substring(int beginIndex)public CharSequence subSequence(int beginIndex, int endIndex)
获取 [ beginIndex , endIndex/length) 位置的子串
==后续补充==
String.split()
单个符号作为分割:
1 | String[] splitAddress=address.split("\\"); // `\` |
多符号作为分割:
如果使用多个分隔符则需要借助 | 符号,但需要转义符的仍然要加上分隔符进行处理
1 | String address="上海^上海市@闵行区#吴中路"; |