Java StringBuffer类API方法指南

x33g5p2x  于2021-08-19 转载在 Java  
字(17.0k)|赞(0)|评价(0)|浏览(376)

在本指南中,我们将讨论Java StringBuffer类的所有构造函数和方法,并附有大量的例子。

关于StringBuffer类的关键点

  • Java的StringBufferclass用于创建一个可变(可修改)的字符串。Java中的StringBufferclass与String类相同,只是它是可变的,也就是说,它可以被改变。
  • Java的StringBufferclass是线程安全的,也就是说,多个线程能同时访问它。所以它是安全的。
  • StringBuffer可以在中间插入字符和子串,或者附加到结尾。StringBuffer会自动增长,为这种添加腾出空间,通常预分配的字符比实际需要的多,以便为增长留出空间。
  • 对StringBuffer的主要操作是append和insert方法,这些方法被重载以接受任何类型的数据。每个方法都有效地将一个给定的数据转换为一个字符串,然后将该字符串的字符追加或插入到字符串缓冲区。append方法总是在缓冲区的末端添加这些字符;insert方法在指定的位置添加这些字符。
  • StringBuffer实现的接口 - Serializable, Appendable, CharSequence

StringBuffer构造函数

StringBuffer定义了这四个构造函数。

  • StringBuffer( )
  • StringBuffer(int size)
  • StringBuffer(String str)
  • StringBuffer(CharSequence chars)

StringBuffer()

构建一个字符串缓冲区,里面没有字符,初始容量为16个字符。例子。

StringBuffer buffer = new StringBuffer();
System.out.println(buffer.capacity());

输出:

16

StringBuffer(int capacity)

构建一个没有字符的字符串缓冲区,并指定初始容量。参数容量为初始容量。该方法抛出NegativeArraySizeException - 如果容量参数小于0。

例如。

StringBuffer buffer4 = new StringBuffer(20);
System.out.println(buffer4.capacity());

输出。

20

StringBuffer(String str)

构建一个初始化为指定字符串内容的字符串缓冲区。字符串缓冲区的初始容量是16加上字符串参数的长度。参数str是缓冲区的初始内容。例子。

StringBuffer buffer2 = new StringBuffer("javaguides");
System.out.println(buffer2.capacity());

输出:

26

注意,上面例子中的容量,它给出的是String长度加上初始容量。

StringBuffer(CharSequence seq)

构造一个字符串缓冲区,包含与指定CharSequence相同的字符。字符串缓冲区的初始容量是16加CharSequence参数的长度。

如果指定的CharSequence的长度小于或等于0,那么将返回一个容量为16的空缓冲区。
例子。

CharSequence charSequence = new StringBuilder("charSequence");
StringBuffer buffer3 = new StringBuffer(charSequence);
System.out.println(buffer3);

输出:

charSequence

StringBuffer APIs/Methods


A图显示了StringBuffer所提供的方法列表 Classappend()方法

它有几个重载版本。

  1. StringBuffer append(boolean b) - 将boolean参数的字符串表示法添加到序列中。
  2. StringBuffer append(char c) - 将char参数的字符串表示法添加到该序列中。
  3. StringBuffer append(char[] str) - 将char数组参数的字符串表示法添加到该序列中。
  4. StringBuffer append(char[] str, int offset, int len) - 将char数组参数的子数组的字符串表示法添加到此序列中。
  5. StringBuffer append(CharSequence s) - 将指定的CharSequence添加到这个序列中。
  6. StringBuffer append(CharSequence s, int start, int end) - 将指定的CharSequence的一个子序列添加到这个序列中。
  7. StringBuffer append(double d) - 将双倍参数的字符串表示法添加到这个序列中。
  8. StringBuffer append(float f) - 在此序列中添加浮动参数的字符串表示。
  9. StringBuffer append(int i) - 将int参数的字符串表示法添加到这个序列中。
  10. StringBuffer append(long lng) - 将长参数的字符串表示法添加到这个序列中。
  11. StringBuffer append(Object obj) - 向这个序列添加Object参数的字符串表示。
  12. StringBuffer append(String str) - 将指定的字符串追加到这个字符序列中。
  13. StringBuffer append(StringBuffer sb) - 将指定的StringBuffer追加到该序列中。
  14. StringBuffer appendCodePoint(int codePoint) - 将codePoint参数的字符串表示附加到这个序列中。
    让我们用例子来证明每个append()方法。

例子。这个程序演示了上述14种append方法的用法。

public class AppendExample {
 public static void main(String[] args) {
  // 14 append overloaded methods

  // Append String
  StringBuffer buffer;
  buffer = new StringBuffer().append("guides");
  System.out.println("Append String : " + buffer);

  // Append char
  buffer = new StringBuffer().append('c');
  System.out.println("Append char : " + buffer);

  // Append Object
  buffer = new StringBuffer().append(new Object().getClass());
  System.out.println("Append Object : " + buffer);

  // Append chars
  char[] chars = { 'j', 'a', 'v', 'a' };
  buffer = new StringBuffer().append(chars);
  System.out.println("Append chars : " + buffer);

  // Append charSequence
  CharSequence charSequence = new String("charSequence");
  buffer = new StringBuffer().append(charSequence);
  System.out.println("Append charSequence : " + buffer);

  // Append Double
  buffer = new StringBuffer().append(10.0d);
  System.out.println("Append Double : " + buffer);

  // Append Float
  buffer = new StringBuffer().append(10.5f);
  System.out.println("Append Float : " + buffer);

  // Append int
  buffer = new StringBuffer().append(100);
  System.out.println("Append int : " + buffer);

  // Append Boolean
  buffer = new StringBuffer().append(true);
  System.out.println("Append Boolean : " + buffer);

  // Append Long
  buffer = new StringBuffer().append(1000);
  System.out.println("Append Long : " + buffer);

  // Append stringbuffer
  buffer = new StringBuffer().append(new StringBuffer("stringbuffer"));
  System.out.println("Append stringbuffer : " + buffer);

  // Appends the string representation of a subarray of the char array
  // argument to this sequence.
  buffer = new StringBuffer().append(chars, 1, 3);
  System.out.println("Appends the string representation of a "
    + " subarray of the char array argument to this sequence.  : " + buffer);

  // Appends a subsequence of the specified CharSequence to this sequence
  buffer = new StringBuffer().append("javaguides", 0, 9);
  System.out.println("Appends a subsequence of the specified " 
  + " CharSequence to this sequence. : " + buffer);

  // Appends the string representation of the codePoint argument to this
  // sequence.
  buffer = new StringBuffer().appendCodePoint(5);
  System.out.println(
    "Appends the string representation of the "
  + " codePoint argument to this sequence.  : " + buffer);
 }
}

输出。

Append String : guides
Append char : c
Append Object : class java.lang.Object
Append chars : java
Append charSequence : charSequence
Append Double : 10.0
Append Float : 10.5
Append int : 100
Append Boolean : true
Append Long : 1000
Append stringbuffer : stringbuffer
Appends the string representation of a  subarray of the char array argument to this sequence.  : ava
Appends a subsequence of the specified  CharSequence to this sequence. : javaguide
Appends the string representation of the  codePoint argument to this sequence.  :

capacity()

该方法返回当前的容量。容量是可用于新插入的字符的存储量,超过这个容量将发生分配。

例子。这个简单的程序演示了capacity()方法的用法。

public class CapacityExample {
    public static void main(String[] args) {
        StringBuffer builder = new StringBuffer("javaguides");
       int capacity = builder.capacity();
  
       // inital capacity
       System.out.println(new StringBuffer().capacity());
  
       // intial capacity 16 + number of characters in string
       System.out.println("Capacity of the string :: " + capacity);
    }
}

输出。

16
Capacity of the string :: 26

charAt(int index)

返回指定索引处的char值。索引范围从0到length()-1。序列的第一个字符值在索引0处,下一个在索引1处,以此类推,如同数组的索引。

为了从一个字符串中提取单个字符,你可以通过charAt( )方法直接引用单个字符。
这个方法会抛出IndexOutOfBoundsException--如果一个索引是负的或者大于等于length()。

例1: 返回这个字符串中指定索引处的char值。第一个char值在索引0处。

StringBuffer buffer = new StringBuffer("Welcome to string handling guide");
char ch1 = buffer.charAt(0);
char ch2 = buffer.charAt(5);
char ch3 = buffer.charAt(11);
char ch4 = buffer.charAt(20);
System.out.println("Character at 0 index is: " + ch1);
System.out.println("Character at 5th index is: " + ch2);
System.out.println("Character at 11th index is: " + ch3);
System.out.println("Character at 20th index is: " + ch4);

输出。

Character at 0 index is: W
Character at 5th index is: m
Character at 11th index is: s
Character at 20th index is: n

例2:抛出IndexOutOfBoundsException的例子 - 如果一个索引是负的或者大于等于length()。

public static void charAtExample2() {
StringBuffer builder = new StringBuffer("Java Guides");
char ch1 = builder.charAt(builder.length());
System.out.println("character :: " + ch1);

输出。

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 11
 at java.lang.StringBuffer.charAt(StringBuffer.java:202)
 at com.javaguides.stringbuffer.methods.ChatAtExample.charAtExample2(ChatAtExample.java:26)
 at com.javaguides.stringbuffer.methods.ChatAtExample.main(ChatAtExample.java:6)

例3:举例说明如何获得字符串的第一个和最后一个字符

public static void charAtExample3() {
StringBuffer buffer = new StringBuffer("Java Guides");
int strLength = buffer.length() - 1;
// Fetching first character
System.out.println("Character at 0 index is: " + buffer.charAt(0));
// The last Character is present at the string length-1 index
System.out.println("Character at last index is: " + buffer.charAt(strLength));

输出。

Character at 0 index is: J
Character at last index is: s

codePointAt(int index)

该方法返回指定索引处的字符(Unicode代码点)。索引指的是char值(Unicode代码单位),范围从0到length()-1。

如果索引参数为负数或不小于这个字符串的长度,该方法会抛出IndexOutOfBoundsException。
例子。

public class CodePointAtExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  int unicode = buffer.codePointAt(0);
  System.out.println("the character (Unicode code point) at the specified index is :: " + unicode);
 }
}

输出;

the character (Unicode code point) at the specified index is :: 106

codePointBefore(int index)

该方法返回指定索引之前的字符(Unicode码位)。索引指的是char值(Unicode代码单位),范围从1到长度。

该方法抛出IndexOutOfBoundsException - 如果索引参数为负数或不小于该字符串的长度。
例子。

public class CodePointBeforeExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  int unicode = buffer.codePointBefore(1);
  System.out.println("the character (Unicode code point)"
    + "  at the before specified index is :: " + unicode);
 }
}

输出:

the character (Unicode code point) at the before specified index is :: 106

codePointCount(int beginIndex, int endIndex)

该方法返回该字符串指定文本范围内的Unicode代码点的数量。文本范围从指定的beginIndex开始,延伸到索引endIndex-1的字符。

如果beginIndex为负数,或者endIndex大于此字符串的长度,或者beginIndex大于endIndex,此方法会抛出IndexOutOfBoundsException。
例子。

public class CodePointCountExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  System.out.println("length of the string :: " + buffer.length());
  int unicode = buffer.codePointCount(0, buffer.length());
  System.out.println("the character (Unicode code point) "
    + " at the specified index is :: " + unicode);
 }
}

输出:

length of the string :: 10
the character (Unicode code point)  at the specified index is :: 10

delete(int start, int end)

这个方法删除这个序列的一个子串中的字符。子串从指定的start开始,延伸到索引end-1的字符,如果没有这样的字符,则延伸到序列的末端。如果start等于end,则不做任何改变。

例子。使用delete()方法从字符串'javaguides'中删除子串'java'的例子。

public class DeleteExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  
  // start with index and end with end -1
  StringBuffer subBuffer = buffer.delete(0, 4);
  System.out.println("Delete string 'java' from string 'javaguides' : " + subBuffer.toString());
 }
}

输出。

Delete string 'java' from string 'javaguides' : guides

deleteCharAt(int index)

这个方法删除这个序列中指定位置上的char。这个序列被缩短了一个字符。

这个方法抛出了StringIndexOutOfBoundsException - 如果索引是负的或者大于等于length()。
例子。使用deleteCharAt()方法从字符串 "javaguides "中删除字符 "g "的例子。

输出。

Delete char 'g' from string 'javaguides' : javauides

ensureCapacity(int minimumCapacity)

确保容量至少等于指定的最小值。如果当前容量小于参数,那么将分配一个新的内部数组,其容量更大。新的容量是以下两者中较大的。

  • 最小容量参数。
  • 旧容量的两倍,加上2。
    例子。使用ensureCapacity()方法来确保字符串缓冲区的容量的例子。
public class EnsureCapacityExample {
 public static void main(String[] args) {
  StringBuffer builder = new StringBuffer();
  builder.ensureCapacity(11);
     System.out.println(builder.capacity());
     builder.ensureCapacity(17);
     System.out.println(builder.capacity());
 }
}

输出:

16
34

getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

从这个序列中的字符被复制到目标字符数组dst中。

例子。这是一个将字符从这个序列复制到目标字符数组dst的例子。

public class GetCharsExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  char[] dst = new char[buffer.length()];
  buffer.getChars(0, buffer.length(), dst, 0);
  
  for (char c : dst) {
   System.out.println(c);
  }
 }
}

输出。

j
a
v
a
g
u
i
d
e
s

indexOf()方法

有两种形式的indexOf()方法

  • indexOf(String str) - 返回指定子串的第一次出现在这个字符串中的索引。
  • indexOf(String str, int fromIndex)- 返回指定的子串在这个字符串中第一次出现的索引,从指定的索引开始。
    例子。这是一个简单的程序,用来演示2个具有不同签名的indexOf()方法。
public class IndexOfExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  
  // method 1
  int index = buffer.indexOf("guides");
  System.out.println(index);
  
  // method2
  index = buffer.indexOf("guides", 3);
  System.out.println(index);
 }
}

输出:

4
4

insert()方法

insert()方法有12个重载版本。

  1. StringBuffer insert(int offset, boolean b) - 在这个序列中插入布尔参数的字符串表示。
  2. StringBuffer insert(int offset, char c) - 将char参数的字符串表示法插入到这个序列中。
  3. StringBuffer insert(int offset, char[] str) - 在此序列中插入char数组参数的字符串表示。
  4. StringBuffer insert(int index, char[] str, int offset, int len) - 在这个序列中插入str数组参数的子数组的字符串表示。
  5. StringBuffer insert(int dstOffset, CharSequence s) - 将指定的CharSequence插入这个序列中。
  6. StringBuffer insert(int dstOffset, CharSequence s, int start, int end) - 将指定的CharSequence的一个子序列插入到这个序列。
  7. StringBuffer insert(int offset, double d) - 在这个序列中插入双倍参数的字符串表示。
  8. StringBuffer insert(int offset, float f) - 在这个序列中插入浮动参数的字符串表示。
  9. StringBuffer insert(int offset, int i) - 在这个序列中插入第二个int参数的字符串表示。
  10. StringBuffer insert(int offset, long l) - 在这个序列中插入长参数的字符串表示。
  11. StringBuffer insert(int offset, Object obj) - 将Object参数的字符串表示法插入到这个字符序列中。
  12. StringBuffer insert(int offset, String str) - 将字符串插入到这个字符序列中。
    例子。下面的简单程序演示了所有insert()重载方法的用法。
public class InsertExample {
 public static void main(String[] args) {
  
  // 12 insert overloaded method
  StringBuffer builder = new StringBuffer("javaguides").insert(1,true);
  System.out.println(builder.toString());
  
  builder = new StringBuffer("javaguides").insert(0, 'J');
  System.out.println(builder.toString());
  
  char[] chars = {'d','e','v','e','l','o','p','e','r'};
  builder = new StringBuffer("javaguides").insert(4, chars);
  System.out.println(builder.toString());
  
  CharSequence charSequence = new StringBuilder("J2EE/");
  builder = new StringBuffer("javaguides").insert(0, charSequence);
  System.out.println(builder.toString());
  
  builder = new StringBuffer("javaguides").insert(0, 100.0d);
  System.out.println(builder.toString());
  
  builder = new StringBuffer("javaguides").insert(0, 100.0f);
  System.out.println(builder.toString());
  
  builder = new StringBuffer("javaguides").insert(0, 100);
  System.out.println(builder.toString());
  
  builder = new StringBuffer("javaguides").insert(0, 100l);
  System.out.println(builder.toString());
  
  builder = new StringBuffer("javaguides").insert(0, new Object());
  System.out.println(builder.toString());
  
  builder = new StringBuffer("javaguides").insert(0, "ultimate");
  System.out.println(builder.toString());
  
  builder = new StringBuffer("javaguides").insert(0, chars, 0, chars.length);
  System.out.println(builder.toString());
  
  builder = new StringBuffer("javaguides").insert(0, charSequence, 0, charSequence.length());
  System.out.println(builder.toString());
  
 }
}

输出:

jtrueavaguides
Jjavaguides
javadeveloperguides
J2EE/javaguides
100.0javaguides
100.0javaguides
100javaguides
100javaguides
java.lang.Object@15db9742javaguides
ultimatejavaguides
developerjavaguides
J2EE/javaguides

lastIndexOf()方法

lastIndexOf()方法有两个重载版本。下面是它的所有形式。

int lastIndexOf(String str) - 返回这个字符串中指定子串的最右边出现的索引。
int lastIndexOf(String str, int fromIndex)- 返回指定子串最后出现在这个字符串中的索引。
例子。这个例子演示了2lastIndexOf()重载方法的用法。

public class LastIndexOfExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  
  // method1
  int lastIndexOf = buffer.lastIndexOf("guides");
  System.out.println(" last index of given string 'guides' in' "
      + buffer.toString()+"' ::  " + lastIndexOf);
  
  // method 2
  lastIndexOf = buffer.lastIndexOf("java", 3);
  System.out.println(" last index of given string 'java' in' "
      + buffer.toString()+"' ::  " + lastIndexOf);
 }
}

输出:

last index of given string 'guides' in' javaguides' ::  4
 last index of given string 'java' in' javaguides' ::  0

length()

返回长度(字符数)。

例子。

public class LengthExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  int length = buffer.length();
  System.out.println(" length of the string '" + buffer + "' is :: " + length);
 }
}

输出。

length of the string 'javaguides' is :: 10

replace(int start, int end, String str)

用指定的String中的字符替换这个序列的子串中的字符。子串从指定的起始点开始,延伸到索引端-1的字符,如果没有这样的字符,则延伸到序列的末端。首先,子串中的字符被删除,然后在开始处插入指定的字符串。(如果有必要,这个序列将被延长以适应指定的字符串)。)

例子。使用replace()方法将字符串 "ja "替换为字符串 "java "的例子。

public class ReplaceExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("jaguides");
  
  // replace ja with java- start index 0 and end index -1
  StringBuffer subBuffer = buffer.replace(0, 2, "java");
  
  System.out.println(subBuffer);
 }
}

输出。

javaguides

reverse()

导致该字符序列被该序列的反向所取代。

例子。使用reverse()方法反转给定的字符串 "javaguides "的例子。

public class ReverseExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  StringBuffer reverse = buffer.reverse();
  System.out.println("Reversed string :" + reverse);
 }
}

输出。

Reversed string :sediugavaj

setCharAt(int index, char ch)

指定索引处的字符被设置为ch。

例子。使用setCharAt()方法在索引0处设置字符'J'的例子。

public class SetCharExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  buffer.setCharAt(0, 'J');
  System.out.println(buffer.toString());
 }
}

输出。

Javaguides

setLength(int newLength)

设置字符序列的长度。

例子。使用setLength()方法重置StringBuffer的长度的例子。

public class SetLengthExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  System.out.println("Before set length to 0 : " + buffer.length());
  buffer.setLength(0);
  System.out.println("After set length to 0 : " + buffer.length());
 }
}

输出。

Before set length to 0 : 10
After set length to 0 : 0

substring()方法

substring()方法有两个重载版本。

  1. String substring(int start) - 返回一个新的字符串,该字符串包含当前包含在这个字符序列中的一个子序列的字符。
  2. String substring(int start, int end) - 返回一个新的字符串,该字符串包含当前包含在该序列中的字符的子序列。
    例子。这个例子演示了substring()方法的两个重载版本的用法。
public class SubStringExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  
  // substring from start to end
  String subStr = buffer.substring(0, buffer.length());
  System.out.println("substring from 0 to length of the string : " + subStr);
  
  // print java
  System.out.println(buffer.substring(0, 4));
  
  // print guides
  System.out.println(buffer.substring(4, buffer.length()));
 }
}

输出:

substring from 0 to length of the string : javaguides
java
guides

toString()

返回一个代表该序列中数据的字符串。

例如。

public class ToStringExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  System.out.println(buffer.toString());
 }
}

输出。

javaguides

trimToSize()

试图减少用于字符序列的存储空间。

例子。

public class TrimToSizeExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides ");
  System.out.println(buffer.capacity());
  buffer.trimToSize();
  System.out.println(buffer.capacity());
 }
}

输出。

27
11

查看我的顶级初学者到专家Java String Tutorial

GitHub 仓库

参考资料

相关文章