String

  • 无参数构造函数
    /**
* 底层存储字符串的目标字节数组,
* Jdk 8 之前都是字符数组 private final char[] value;
*/
@Stable
private final byte[] value;
/**
* 编码底层字节数组的字符集,支持 LATIN1、UTF16
*/
private final byte coder;
/**
* 字符串的哈希码值,默认为 0
*/
private int hash; // Default to 0 /**
* 创建一个空字符串
* created by ZXD at 18 Nov 2018 T 11:17:48
*/
public String() {
this.value = "".value;
this.coder = "".coder;
}
  • 基于字节数组创建字符串
    public String(byte[] bytes) {
this(bytes, 0, bytes.length);
} public String(byte bytes[], int offset, int length) {
checkBoundsOffCount(offset, length, bytes.length);
// 对目标字节数组进行编码
StringCoding.Result ret = StringCoding.decode(bytes, offset, length);
// 获取编码后的字节数组
this.value = ret.value;
// 获取编码后的字符集
this.coder = ret.coder;
} public String(byte bytes[], Charset charset) {
this(bytes, 0, bytes.length, charset);
} public String(byte bytes[], int offset, int length, Charset charset) {
// 防御式编程,null 校验
if (charset == null)
throw new NullPointerException("charset");
checkBoundsOffCount(offset, length, bytes.length);
// 根据指定的字符集对字节数组进行编码
StringCoding.Result ret =
StringCoding.decode(charset, bytes, offset, length);
this.value = ret.value;
this.coder = ret.coder;
} public String(byte bytes[], String charsetName)
throws UnsupportedEncodingException {
this(bytes, 0, bytes.length, charsetName);
} public String(byte bytes[], int offset, int length, String charsetName)
throws UnsupportedEncodingException {
if (charsetName == null)
throw new NullPointerException("charsetName");
checkBoundsOffCount(offset, length, bytes.length);
// 根据指定的字符集对字节数组进行编码,编码名称错误时,抛出 UnsupportedEncodingException 异常
StringCoding.Result ret =
StringCoding.decode(charsetName, bytes, offset, length);
this.value = ret.value;
this.coder = ret.coder;
}
  • 基于字符数组创建字符串
    public String(char value[]) {
this(value, 0, value.length, null);
} public String(char value[], int offset, int count) {
this(value, offset, count, rangeCheck(value, offset, count));
} private static Void rangeCheck(char[] value, int offset, int count) {
// 字符串下标合法性校验
checkBoundsOffCount(offset, count, value.length);
return null;
} String(char[] value, int off, int len, Void sig) {
// 特殊场景优化处理
if (len == 0) {
this.value = "".value;
this.coder = "".coder;
return;
}
if (COMPACT_STRINGS) {
// 如果启用压缩,则将字符数组压缩,字符集设置为 LATIN1
byte[] val = StringUTF16.compress(value, off, len);
if (val != null) {
this.value = val;
this.coder = LATIN1;
return;
}
}
// 字符数组不压缩时,字符集设置为 UTF16
this.coder = UTF16;
this.value = StringUTF16.toBytes(value, off, len);
}
  • 字符串内容相等性比较
    public boolean equals(Object anObject) {
// 地址相等则直接返回 true
if (this == anObject) {
return true;
}
// 形参对象为字符串
if (anObject instanceof String) {
String aString = (String)anObject;
// 字符编码相同时才能做比较
if (coder() == aString.coder()) {
return isLatin1() ? StringLatin1.equals(value, aString.value)
: StringUTF16.equals(value, aString.value);
}
}
return false;
}
  • 字符串的长度
    public int length() {
return value.length >> coder();
} byte coder() {
return COMPACT_STRINGS ? coder : UTF16;
} @Native static final byte LATIN1 = 0;
@Native static final byte UTF16 = 1; // Unicode字符集的抽象码位映射为16位长的整数
  • 比较字符串内容并且不区分大小写
    public boolean equalsIgnoreCase(String anotherString) {
return (this == anotherString) ? true
: (anotherString != null) // 形参字符串不为 null
&& (anotherString.length() == length()) // 两个字符串长度一致
&& regionMatches(true, 0, anotherString, 0, length()); // 编码后的区域是否匹配
}
  • 字符串拼接
    public String concat(String str) {
int olen = str.length();
if (olen == 0) {
return this;
} // 字符集相同时,直接通过数组拷贝进行拼接
if (coder() == str.coder()) {
byte[] val = this.value;
byte[] oval = str.value;
int len = val.length + oval.length;
byte[] buf = Arrays.copyOf(val, len);
System.arraycopy(oval, 0, buf, val.length, oval.length);
return new String(buf, coder);
}
int len = length();
// 使用 UTF16 编码计算目标字节数组长度,并将它们都拷贝进去。
byte[] buf = StringUTF16.newBytesFor(len + olen);
getBytes(buf, 0, UTF16);
str.getBytes(buf, len, UTF16);
return new String(buf, UTF16);
}
  • 字符串截取
    public String substring(int beginIndex, int endIndex) {
int length = length();
// 索引合法性检测
checkBoundsBeginEnd(beginIndex, endIndex, length);
int subLen = endIndex - beginIndex;
// 特殊场景优化处理,截取的子字符串就是目标字符串
if (beginIndex == 0 && endIndex == length) {
return this;
}
return isLatin1() ? StringLatin1.newString(value, beginIndex, subLen)
: StringUTF16.newString(value, beginIndex, subLen);
} /**
* 起始索引和结束索引不在 0到 length()-1 范围内,则抛出 IndexOutOfBoundsException 异常
* 结束索引大于起始索引,则抛出 IndexOutOfBoundsException 异常
*/
static void checkBoundsBeginEnd(int begin, int end, int length) {
if (begin < 0 || begin > end || end > length) {
throw new StringIndexOutOfBoundsException(
"begin " + begin + ", end " + end + ", length " + length);
}
}
  • 获取字符串中指定索引处的单个字符
    public char charAt(int index) {
if (isLatin1()) {
return StringLatin1.charAt(value, index);
} else {
return StringUTF16.charAt(value, index);
}
} StringLatin1#charAt
public static char charAt(byte[] value, int index) {
if (index < 0 || index >= value.length) {
throw new StringIndexOutOfBoundsException(index);
}
return (char)(value[index] & 0xff);
}
  • 目标字符串是否包含子字符串
    public boolean contains(CharSequence s) {
return indexOf(s.toString()) >= 0;
}
  • 字符串是否为空
    public boolean isEmpty() {
return value.length == 0;
}
  • 字符串替换
    public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
String ret = isLatin1() ? StringLatin1.replace(value, oldChar, newChar)
: StringUTF16.replace(value, oldChar, newChar);
if (ret != null) {
return ret;
}
}
return this;
} public String replace(CharSequence target, CharSequence replacement) {
// 需要查找的字符序列
String tgtStr = target.toString();
// 需要替换的字符序列
String replStr = replacement.toString();
// 如果要查找的字符序列没有在目标字符串中,则返回其本身
int j = indexOf(tgtStr);
if (j < 0) {
return this;
}
// 查找字符序列的长度
int tgtLen = tgtStr.length();
int tgtLen1 = Math.max(tgtLen, 1);
// 当期字符串的长度
int thisLen = length(); int newLenHint = thisLen - tgtLen + replStr.length();
if (newLenHint < 0) {
throw new OutOfMemoryError();
}
StringBuilder sb = new StringBuilder(newLenHint);
int i = 0;
// 在 StringBuilder 指定的索引处追加字符串,并重新获取要查找的子字符串索引进行循环替换。
do {
sb.append(this, i, j).append(replStr);
i = j + tgtLen;
} while (j < thisLen && (j = indexOf(tgtStr, j + tgtLen1)) > 0);
return sb.append(this, i, thisLen).toString();
}
  • 基于正则表达式替换字符串
    public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
  • 基于正则表达式替换首次出现的字符串
    public String replaceFirst(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
}

String 部分源码分析的更多相关文章

  1. String 类源码分析

    String 源码分析 String 类代表字符序列,Java 中所有的字符串字面量都作为此类的实例. String 对象是不可变的,它们的值在创建之后就不能改变,因此 String 是线程安全的. ...

  2. python string.py 源码分析 三:maketrans

    l = map(chr, xrange(256)) #将ascii转为字符串 _idmap = str('').join(l) del l # Construct a translation stri ...

  3. String类源码分析(JDK1.7)

    以下学习根据JDK1.7String类源代码做注释 public final class String implements java.io.Serializable, Comparable<S ...

  4. python string.py 源码分析 二:capwords

    def capwords(s, sep=None): """capwords(s [,sep]) -> string Split the argument into ...

  5. String类源码分析

    1.String类注释说明 /** * The {@code String} class represents character strings. All * string literals in ...

  6. python string.py 源码分析 一

    # Some strings for ctype-style character classification c风格字符串 whitespace = ' \t\n\r\v\f' #空白字符 \t 制 ...

  7. 【源码分析】你必须知道的string.IsNullOrEmpty && string.IsNullOrWhiteSpace

    写在前面 之前自信撸码时踩了一次小坑,代码如下: private static void AppServer_NewMessageReceived(WebSocketSession session, ...

  8. Java源码分析:关于 HashMap 1.8 的重大更新(转载)

    http://blog.csdn.net/carson_ho/article/details/79373134 前言 HashMap 在 Java 和 Android 开发中非常常见 而HashMap ...

  9. [源码]String StringBuffer StringBudlider(2)StringBuffer StringBuilder源码分析

      纵骑横飞 章仕烜   昨天比较忙 今天把StringBuffer StringBulider的源码分析 献上   在讲 StringBuffer StringBuilder 之前 ,我们先看一下 ...

随机推荐

  1. 将本地的java项目提交到github出错解决

    1.我们新建一个了java项目后,需要提交到github进行版本控制 2.如果此时github中的仓库不为空,我们在本地使用git push提交时会报以下错误, ! [rejected]       ...

  2. linux下mysql的常用命令

    更改mysql数据库root的密码 首次进入数据库是不用密码的: [root@localhost ~]# /usr/local/mysql/bin/mysql -uroot Welcome to th ...

  3. xml发post请求

    # python3字符串换行,在右边加个反斜杠 body = '<?xml version="1.0" encoding = "UTF-8"?>' ...

  4. Hibernate 最简单实例

    我从网上下载了 hibernate-release-4.3.0.Final.zip,解压缩,把/lib/required文件夹下的所有jar包加入到eclipse项目中的Referenced Libr ...

  5. usermod 修改用户信息

    7.2 usermod 修改用户信息 1.命令功能 usermod 修改已存在的用户账号信息. 2.语法格式 usermod option login 参数选项说明 选项 选项说明 -c 修改用户pa ...

  6. 三、Ubuntu16.04 安装Jira8.2.2(自带中文包)和破解

    一.环境准备 (一)安装java Jira7.2的运行是依赖java环境的,也就是说需要安装jdk并且要是1.8以上版本,如下: java -version没有任何显示需要下载安装 1.下载链接:ht ...

  7. 通过telnet自动下载cfg配置文件

    源代码如下: import telnetlib import logging import datetime import csv import time def telnetfunc(enbid, ...

  8. HashMap的底层实现以及解决hash值冲突的方式

    class HashMap<K,V> extends AbstractMap<K,V> HashMap  put() HashMap  get() 1.put() HashMa ...

  9. uwsgi 的启动、停止、重启

    ## 一.概念释义### WSGI WSGI 是一个Web服务器(如nginx)与应用服务器(如uWSGI)通信的一种规范(协议).官方定义是,the Python Web Server Gatewa ...

  10. springboot使用外部application.properties配置文件

    一.背景介绍 springboot默认的application.properties文件只能在项目内部,如果打成docker镜像后配置文件也打进去了,这样每次需要改动配置(比如数据库的连接信息)就需要 ...