7.3.3 Java9改进的String、 StringBuffer和StringBuilder类

7.3.3 Java9改进的String StringBuffer和StringBuilder类

字符串就是一连串的字符序列,Java提供了StringStringBufferStringBuilder三个类来封装字符串,并提供了一系列方法来操作字符串对象。

String介绍

String类是不可变类,即一旦一个String对象被创建以后,包含在这个对象中的字符序列是不可改的,直至这个对象被销毁。

StringBuffer介绍

StringBuffer对象则代表一个字符序列可变的字符串,当一个String Buffer被创建以后,通过String Buffer提供的append()insert()reverse()setCharAt()setLength()等方法可以改变这个字符串对象的字符序列。一旦通过StringBuffer生成了最终想要的字符串,就可以调用它的toString()方法将其转换为一个String对象.
StringBuilder类是JDK1.5新增的类,它也代表可变字符串对象。实际上, StringBuilderStringBuffer基本相似,两个类的构造器和方法也基本相同。

StringBuilder和StringBuffer的不同

StringBuffer是线程安全的,而StringBuilder则没有实现线程安全功能,所以性能略高。
因此在通常情况下,如果需要创建一个内容可变的字符串对象,则应该优先考虑使用StringBuilder,需要考虑线程安全的使用StringBuffer类。

CharSequence接口介绍

StringStringBuilderStringBuffer都实现了CharSequence接口,因此CharSequence可认为是一个字符串的协议接口。

java9对字符串类的改进

Java9改进了字符串的实现(包括StringStringBufferStringBuilder)。

  • Java9以前字符串采用char数组来保存字符,因此字符串的每个字符占2字节;
  • Java9的字符串采用byte数组再加一个encoding-flag字段来保存字符,因此字符串的每个字符只占1字节

所以Java9的字符串更加节省空间,但字符串的功能方法没有受到任何影响。

String API详解

String类提供了大量构造器来创建String对象,其中如下几个有特殊用途。

String类构造器

构造器 描述
String() 创建一个包含0个字符串序列的String对象.
String(byte[] bytes, Charset charset) 使用指定的字符集将指定的byte数组解码成一个新的String对象。
String(byte[] bytes, int offset,int length) 使用平台的默认字符集将指定的byte数组从offset位置开始、取出长度为length的子数组,然后解码成一个新的String对象。
String(byte[] bytes, int offset, int length, String charsetName) 使用指定的字符集将指定的byte数组从offset开始、取出长度为length的子数组,然后解码成一个新的String对象。
String(char[] value, int offset, int count) 将指定的字符数组从offset开始、取出长度为count的字符元素,然后连缀成字符串。
String(String original) 根据字符串直接量来创建一个String对象。也就是说,新创建的String对象是该参数字符串的副本
String(StringBuffer buffer) 根据StringBuffer对象来创建对应的String对象。
String(StringBuilder builder) 根据StringBuilder对象来创建对应的String对象。

String类方法

String类也提供了大量方法来操作字符串对象,下面详细介绍这些常用方法

根据下标获取一个字符

方法 描述
char charAt(int index) 获取字符串中指定位置的字符。其中,参数index指的是字符串的序数,字符串的序数从0开始到length()-1

复制字符序列到字符数组的方法

方法 描述
void getChars(int srcBegin, int srcEnd,char[] dst, int dstBegin) 该方法将字符串中从srcBegin开始,到srcEnd结束的字符复制到dst字符数组中,其中dstBegin为目标字符数组的起始复制位置。

获取字符长度的方法

方法 描述
int length() 返回当前字符串长度。

比较是否相同的方法

方法 描述
boolean contentEquals(StringBuffer sb) 将该String对象与StringBuffer对象进行比较,当它们包含的字符序列相同时返回true
boolean equals(Object anObject) 将该字符串与指定对象比较,如果二者包含的字符序列相等则返回true;否则返回false
boolean equalsIgnoreCase(String str) 与前一个方法基本相似,只是忽略字符的大小写。

生成新字符串的方法

方法 描述
String concat(String anotherString) 将该String对象与anotherString连接在一起。与Java提供的字符串连接运算符"+"的功能相同。
String replace(char oldChar, char newChar) 将字符串中的第一个oldChar替换成newChar.
String substring(int beginIndex) 获取从beginIndex位置开始到结束的子字符串。
String substring(int beginIndex, int endIndex) 获取从beginIndex位置开始到endIndex位置的子字符串。

静态方法

方法 描述
static String valueOf(X x) 一系列用于将基本类型值转换为String对象的方法。
static String copyValueOf(char[] data) 将字符数组连缀成字符串,与构造器String(char[] content)的功能相同
static String copyValueof(char[] data, int offset, int count) char数组的子数组中的元素连缀成字符串,与构造器String(char[] value, int offset, int count)的功能相同。

比较大小方法

方法 描述
int compareTo(String anotherString) 比较两个字符串的大小。
  • 如果两个字符串的字符序列相等,则返回0;
  • 如果两个字符串的字符序列不相等,则从两个字符串第0个字符开始比较,返回第一个不相等的字符差
  • 如果较长字符串的前面部分恰巧是较短的字符串,则返回它们的长度差

查找字符出现位置的方法

方法 描述
int indexOf(int ch) 找出ch字符在该字符串中第一次出现的位置.
int indexOf(int ch, int fromIndex) 找出ch字符在该字符串中从fromIndex开始后第一次出现的位置。
int indexOf(String string) 找出string子字符串在该字符串中第一次出现的位置。
int indexOf(String string, int fromIndex) 找出string子字符串在该字符串中从fromIndex开始后第一次出现的位置。
int lastIndexOf( int ch) 找出ch字符在该字符串中最后一次出现的位置.
int lastIndexOf(int ch, int fromIndex) 找出ch字符在该字符串中从fromIndex开始后最后一次出现的位置
int lastIndexOf(String str) 找出str子字符串在该字符串中最后一次出现的位置。
int lastIndexOf(String str,int fromIndex) 找出str子字符串在该字符串中从fromIndex开始后最后次出现的位置。

大小写转换方法

方法 描述
String toLowerCase() 将字符串转换成小写。
String toUpperCase() 将字符串转换成大写。

转成字节数组或字符数组的方法

方法 描述
byte[] getBytes() 将该String对象转换成byte数组。
char[] toCharArray() 将该String对象转换成char数组。

判断是否带前缀或后缀

方法 描述
boolean startsWith(String prefix) String对象是否以prefix开始。
boolean startsWith(String prefix, int offset) String对象从offset位置算起,是否以prefix开始。
boolean endswith(String suffix) 返回该Sing对象是否以suffix结尾。

StringBuffer和StringBuilder

String类是不可变的, String的实例一旦生成就不会再改变了,使用字符串会产生字符串直接量,通过连接符+也会产生字符串直接量。
因为String是不可变的,所以会额外产生很多临时变量,使用StringBufferStringBuilder就可以避免这个问题。
StringBuilder提供了一系列插入追加改变该字符串里包含的字符序列的方法。而StringBuffer与其用法完全相同,只是**StringBuffer是线程安全的**。

StringBuilder和StringBuffer的属性

StringBuilderStringBuffer有两个属性:lengthcapacity,其中

  1. length属性表示其包含的字符序列的长度。与String对象的length不同的是, StringBuilderStringBufferlength是可以改变的,可以通过lengthsetLength( int len)方法来访问和修改其字符序列的长度。
  2. capacity属性表示StringBuilder容量, capacity通常比length大,程序通常无须关心capacity属性。如下程序示范了StringBuilder类的用法。
  • StringBuilderlength方法返回其字符序列的长度,
  • StringBuildercapacity()方法的返回值是容量,容量比length返回值大。

StringBuilder类有追加插入替换删除,反转等操作,这些操作可以改变了StringBuilder里的字符序列。

StringBuilder方法详解

追加方法

方法 描述
StringBuilder append(boolean b) 追加布尔参数到StringBuilder中
StringBuilder append(char c) 追加char参数到StringBuilder中
StringBuilder append(char[] str) Appends the string representation of the char array argument to this sequence.
StringBuilder append(char[] str, int offset, int len) Appends the string representation of a subarray of the char array argument to this sequence.
StringBuilder append(CharSequence s) Appends the specified character sequence to this Appendable.
StringBuilder append(CharSequence s, int start, int end) Appends a subsequence of the specified CharSequence to this sequence.
StringBuilder append(double d) Appends the string representation of the double argument to this sequence.
StringBuilder append(float f) Appends the string representation of the float argument to this sequence.
StringBuilder append(int i) Appends the string representation of the int argument to this sequence.
StringBuilder append(long lng) Appends the string representation of the long argument to this sequence.
StringBuilder append(Object obj) Appends the string representation of the Object argument.
StringBuilder append(String str) Appends the specified string to this character sequence.
StringBuilder append(StringBuffer sb) Appends the specified StringBuffer to this sequence.
StringBuilder appendCodePoint(int codePoint) Appends the string representation of the codePoint argument to this sequence.

删除方法

方法 描述
StringBuilder delete(int start, int end) Removes the characters in a substring of this sequence.
StringBuilder deleteCharAt(int index) Removes the char at the specified position in this sequence.

插入方法

方法 描述
StringBuilder insert(int offset, boolean b) Inserts the string representation of the boolean argument into this sequence.
StringBuilder insert(int offset, char c) Inserts the string representation of the char argument into this sequence.
StringBuilder insert(int offset, char[] str) Inserts the string representation of the char array argument into this sequence.
StringBuilder insert(int index, char[] str, int offset, int len) Inserts the string representation of a subarray of the str array argument into this sequence.
StringBuilder insert(int dstOffset, CharSequence s) Inserts the specified CharSequence into this sequence.
StringBuilder insert(int dstOffset, CharSequence s, int start, int end) Inserts a subsequence of the specified CharSequence into this sequence.
StringBuilder insert(int offset, double d) Inserts the string representation of the double argument into this sequence.
StringBuilder insert(int offset, float f) Inserts the string representation of the float argument into this sequence.
StringBuilder insert(int offset, int i) Inserts the string representation of the second int argument into this sequence.
StringBuilder insert(int offset, long l) Inserts the string representation of the long argument into this sequence.
StringBuilder insert(int offset, Object obj) Inserts the string representation of the Object argument into this character sequence.
StringBuilder insert(int offset, String str) Inserts the string into this character sequence.

查找下标方法

方法 描述
int indexOf(String str) Returns the index within this string of the first occurrence of the specified substring.
int indexOf(String str, int fromIndex) Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
int lastIndexOf(String str) Returns the index within this string of the rightmost occurrence of the specified substring.
int lastIndexOf(String str, int fromIndex) Returns the index within this string of the last occurrence of the specified substring.

获取或设置字符方法

方法 描述
char charAt(int index) Returns the char value in this sequence at the specified index.
void setCharAt(int index, char ch) The character at the specified index is set to ch.

容量和长度相关方法

方法 描述
int capacity() Returns the current capacity.
int length() Returns the length (character count).
void setLength(int newLength) Sets the length of the character sequence.
void ensureCapacity(int minimumCapacity) Ensures that the capacity is at least equal to the specified minimum.

截取子串方法

方法 描述
String substring(int start) Returns a new String that contains a subsequence of characters currently contained in this character sequence.
String substring(int start, int end) Returns a new String that contains a subsequence of characters currently contained in this sequence.
CharSequence subSequence(int start, int end) Returns a new character sequence that is a subsequence of this sequence.

反转方法

方法 描述
StringBuilder reverse() Causes this character sequence to be replaced by the reverse of the sequence.

替换方法

方法 描述
StringBuilder replace(int start, int end, String str) Replaces the characters in a substring of this sequence with characters in the specified String.

重写的Object方法

方法 描述
String toString() Returns a string representing the data in this sequence.

代码点相关方法

方法 描述
int offsetByCodePoints(int index, int codePointOffset) Returns the index within this sequence that is offset from the given index by codePointOffset code points.
int codePointAt(int index) Returns the character (Unicode code point) at the specified index.
int codePointBefore(int index) Returns the character (Unicode code point) before the specified index.
int codePointCount(int beginIndex, int endIndex) Returns the number of Unicode code points in the specified text range of this sequence.

其他方法

方法 描述
void trimToSize() Attempts to reduce storage used for the character sequence.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) Characters are copied from this sequence into the destination character array dst.

StringBuilderString之间区别

  • StringBuilder的字符序列是可变的。
  • String的是不可变的