0
点赞
收藏
分享

微信扫一扫

String源码分析(二)

String源码分析(二)_数组

🍁 作者:知识浅谈,CSDN博客专家,阿里云签约博主,InfoQ签约博主,华为云云享专家,51CTO明日之星

📌 擅长领域:全栈工程师、爬虫、ACM算法

💒 公众号:知识浅谈

String源码分析(二)总结 🤞这次都给他拿下🤞

正菜来了⛳⛳⛳

🎈String源码中的相关函数解析

🍮String(bytes[], offset, length,charsetName)

含义:这个构造函数主要是根据byte数组中指定的offset偏移量和length来确定其截取的范围,并按照charsetName指定的方式解码。

public String(byte bytes[], int offset, int length, String charsetName)
throws UnsupportedEncodingException {
if (charsetName == null)
throw new NullPointerException("charsetName");
checkBounds(bytes, offset, length);
this.value = StringCoding.decode(charsetName, bytes, offset, length);
}

🍮String(byte bytes[])

含义:这个函数是指定传入的byte字节数组,函数内部调用String类自身的三个参数的构造函数。

public String(byte bytes[]) {
this(bytes, 0, bytes.length);
}

🍮String(StringBuffer buffer)

含义:这个函数的含义主要是把传递过来额度字节数组赋值给当前的String中的底层数组,分配一个新字符串,该字符串包含字符串缓冲区参数中当前包含的字符序列。复制字符串缓冲区的内容;字符串缓冲区的后续修改不会影响新创建的字符串。

public String(StringBuffer buffer) {
synchronized(buffer) {
this.value = Arrays.copyOf(buffer.getValue(), buffer.length());
}
}

和上边的方法一样,String(StringBuilder builder)也是采用的类似上述的方法。

🍮int length()

含义:这个函数的含义主要就是返回字符串的长度。

public int length() {
return value.length;
}

🍮isEmpty()

含义:这个函数的意思是判断value数组的长度是否为空

public boolean isEmpty() {
return value.length == 0;
}

🍮char charAt(int index)

含义:这个函数的含义是在指定的数组中查找到对应位置的元素,如果超出了返回就会抛出异常。

public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}

🍮int codePointAt(int index)

含义:返回指定索引处的字符(Unicode 代码点)。索引指的是 char 值(Unicode 代码单元),范围从 0 到 length()-1。如果给定索引处指定的 char 值在高代理范围内,则以下索引小于此 String 的长度, 且后面索引处的 char 值在低代理范围内,则返回该代理对对应的补充码位。否则,返回给定索引处的 char 值。 通俗解释:返回String中指定位置的字符对应的Unicode值。

public int codePointAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return Character.codePointAtImpl(value, index, value.length);
}

🍮int codePointBefore(int index)

含义: 和上边的函数基本一样,只不过这个查找的是对应索引的前一个字符的值。

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);
}

🍮int codePointCount(int beginIndex, int endIndex)

含义:这个函数主要是返回指定范围的Unicode 代码点的数量。因为在char数组中有可能某个位置上的字符代表的不是字符。

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相关的函数解读,希望有所帮助,Written By ​​知识浅谈​​

举报

相关推荐

0 条评论