Java StringBuffer类

来源:这里教程网 时间:2026-02-17 21:13:37 作者:

Java StringBuffer类

StringBufferString 的一个同级类,提供了字符串的大部分功能。字符串表示固定长度、不可改变的字符序列,而StringBuffer表示可增长和可写入的字符序列。 StringBuffer 可以在中间插入字符和子串,或者追加到结尾。它会自动增长,以便为这些添加的内容腾出空间,通常预分配的字符比实际需要的多,以便为增长留出空间。

StringBuffer类 用于创建可变(可修改)的字符串。java中的StringBuffer类与String类相同,只是它是可变的,也就是说,它可以被改变。

StringBuffer类的重要构造函数

StringBuffer(): 创建一个空的字符串缓冲区,初始容量为16。StringBuffer(String str): 用指定的字符串创建一个字符串缓冲区。StringBuffer(int capacity): 创建一个空的字符串缓冲区,其容量为指定的长度。

1) append()方法

append()方法将给定的参数与这个字符串连接起来。

例子

import java.io.* ; class A {    public static void main(String args[])    {        StringBuffer sb = new StringBuffer("Hello ");        sb.append("Java"); // now original string is changed        System.out.println(sb);    }}

2) insert()方法

insert()方法在给定的位置插入给定的字符串与这个字符串。

例子。

import java.io.* ; class A {    public static void main(String args[])    {        StringBuffer sb = new StringBuffer("Hello ");        sb.insert(1, "Java");        // Now original string is changed        System.out.println(sb);    }}

3) replace()方法

replace()方法从指定的beginIndex和endIndex-1替换给定的字符串。

例子。

import java.io.* ; class A{     public static void main(String args[]){         StringBuffer sb=new StringBuffer("Hello");         sb.replace(1,3,"Java");         System.out.println(sb);    } }

4) delete()方法

StringBuffer类的delete()方法删除了从指定的beginIndex到endIndex-1的字符串。例如
import java.io.* ; class A{     public static void main(String args[]){         StringBuffer sb=new StringBuffer("Hello");         sb.delete(1,3);         System.out.println(sb);    } }

5) reverse()方法

StringBuilder类的reverse()方法可以反转当前字符串。例子。

import java.io.* ; class A {    public static void main(String args[])    {        StringBuffer sb = new StringBuffer("Hello");        sb.reverse();        System.out.println(sb);    }}

6) capacity()方法

StringBuffer类的capacity()方法返回缓冲区的当前容量。缓冲区的默认容量是16。如果字符数从当前的容量增加,它的容量将增加(oldcapacity*2)+2。例如,如果你的当前容量是16,它将是(16*2)+2=34。例如:
import java.io.* ; class A {    public static void main(String args[])    {        StringBuffer sb = new StringBuffer();        System.out.println(sb.capacity()); // default 16        sb.append("Hello");        System.out.println(sb.capacity()); // now 16        sb.append("java is my favourite language");        System.out.println(sb.capacity());        // Now (16*2)+2=34     i.e (oldcapacity*2)+2    }}

关于StringBuffer类的一些有趣的事实

请记住以下几点: ****

java.lang.StringBuffer扩展(或继承)于Object类。StringBuffer类的所有实现接口。Serializable, Appendable, CharSequence.public final class StringBuffer extends Object implements Serializable, CharSequence, Appendable.字符串缓冲区对于多线程使用是安全的。这些方法可以在任何必要的地方被同步,以便对任何特定实例的所有操作都表现得像它们以某种串行顺序发生。每当涉及源序列的操作发生时(如从源序列中追加或插入),该类只在执行操作的字符串缓冲区上同步,而不是在源上。它继承了Object类的一些方法,如 clone(), equals(), finalize(), getClass(), hashCode(), notifies() _, notifyAll()。_

记住: StringBuilder,J2SE 5为Java已经强大的字符串处理能力增加了一个新的字符串类。这个新的类被称为StringBuilder。它与StringBuffer相同,除了一个重要的区别:它不是同步的,这意味着它不是线程安全的。StringBuilder的优点是性能更快。然而,在使用多线程的情况下,你必须使用StringBuffer而不是StringBuilder。

StringBuffer类的构造函数

1.StringBuffer() : 它保留了16个字符的空间,无需重新分配。

StringBuffer s = new StringBuffer();

2. StringBuffer( int size) : 它接受一个整数参数,明确设置缓冲区的大小。

StringBuffer s = new StringBuffer(20);

3. StringBuffer(String str): 它接受一个字符串参数,该参数设置了StringBuffer对象的初始内容,并保留了再容纳16个字符的空间,而无需重新分配。

StringBuffer s = new StringBuffer("GeeksforGeeks");

StringBuffer类的方法

方法执行的动作
append()用于在现有文本的末尾添加文本。
length()StringBuffer的长度可以通过length()方法找到。
capacity()可以通过capacity()方法找到分配的总容量
charAt()该方法返回该序列中指定索引处的char值。
delete()从调用的对象中删除一个字符序列
deleteCharAt()删除由 loc 指定的索引处的字符。
ensureCapacity()确保容量至少等于给定的最小值。
insert()在指定的索引位置插入文本
length()返回字符串的长度
reverse()将StringBuffer对象中的字符反转。
replace()在一个StringBuffer对象中用另一组字符替换一组字符

注意: 除此之外,所有在String类中使用的方法也都可以使用。这些辅助方法如下。

ensureCapacity() : 它用于增加StringBuffer对象的容量。新的容量将被设置为我们指定的值或当前容量的两倍加2(即容量+2),以较大者为准。这里,容量指定了缓冲区的大小。

语法

void ensureCapacity(int capacity)
appendCodePoint(int codePoint) : 此方法将codePoint参数的字符串表示附加到此序列中。

语法

public StringBuffer appendCodePoint(int codePoint)

charAt(int index): 此方法返回此序列中指定索引处的char值。

语法

public char charAt(int index)

IntStream chars() : 该方法返回一个由该序列的char值组成的int zero-extending流。

语法

public IntStream chars()

int codePointAt(int index) : 该方法返回指定索引处的字符(Unicode 码位)。

语法

public int codePointAt(int index)

int codePointBefore(int index) : 该方法返回指定索引前的字符(Unicode码位)。

语法

public int codePointBefore(int index)

int codePointCount(int beginIndex, int endIndex) : 此方法返回此序列中指定文本范围内的Unicode代码点的数量。

语法

public int codePointCount(int beginIndex, int endIndex)

IntStream codePoints() : 该方法返回该序列的码点值流。

语法

public IntStream codePoints()

void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) : 在这个方法中,字符被从这个序列复制到目标字符数组dst中。

语法

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

int indexOf(String str) : 该方法返回指定子串第一次出现在这个字符串中的索引。

语法

public int indexOf(String str)public int indexOf(String str, int fromIndex)

int lastIndexOf(String str) : 该方法返回指定子串最后出现在这个字符串中的索引。

语法

public int lastIndexOf(String str)public int lastIndexOf(String str, int fromIndex)

int offsetByCodePoints(int index, int codePointOffset) :此方法返回此序列中与给定索引偏移了codePointOffset代码点的索引。

语法

public int offsetByCodePoints(int index, int codePointOffset) 

void setCharAt(int index, char ch) : 在这个方法中,指定索引处的字符被设置为ch。

语法

public void setCharAt(int index, char ch)

void setLength(int newLength) : 此方法设置字符序列的长度。

语法

public void setLength(int newLength)

CharSequence subSequence(int start, int end) : 此方法返回一个新的字符序列,它是此序列的一个子序列。

语法

public CharSequence subSequence(int start, int end)

String substring(int start) : 该方法返回一个新的字符串,该字符串包含当前包含在该字符序列中的一个子序列的字符。

语法

public String substring(int start)public String substring(int start,int end)

String toString() : 此方法返回一个代表此序列中数据的字符串。

语法

public String toString()

void trimToSize() : 该方法试图减少用于字符序列的存储空间。

语法

public void trimToSize()

以上我们只讨论了最广泛使用的方法,并对它们进行了严格的约束,因为它们在编程高手中被广泛使用。

实现

例1: length()和capacity()方法

// Java Program to Illustrate StringBuffer class// via length() and capacity() methods // Importing I/O classesimport java.io.*; // Main classclass GFG {     // main driver method    public static void main(String[] args)    {         // Creating adn storing string by creating object of        // StringBuffer        StringBuffer s = new StringBuffer("GeeksforGeeks");         // Getting the length of the string        int p = s.length();         // Getting the capacity of the string        int q = s.capacity();         // Printing the length and capacity of        // above generated input string on console        System.out.println("Length of string GeeksforGeeks="                           + p);        System.out.println(            "Capacity of string GeeksforGeeks=" + q);    }}

输出

Length of string GeeksforGeeks=13Capacity of string GeeksforGeeks=29

例2:append()

它用于在现有文本的末尾添加文本。

下面是它的几种形式。

StringBuffer append(String str)StringBuffer append(int num)
// Java Program to Illustrate StringBuffer class// via append() method // Importing required classesimport java.io.*; // Main classclass GFG {     // Main driver method    public static void main(String[] args)    {        // Creating an object of StringBuffer class and        // passing random string        StringBuffer s = new StringBuffer("Geeksfor");         // Usage of append() method        s.append("Geeks");         // Returns GeeksforGeeks        System.out.println(s);         s.append(1);        // Returns GeeksforGeeks1        System.out.println(s);    }}

输出

GeeksforGeeksGeeksforGeeks1

例3:insert()

它用于在指定的索引位置插入文本。

语法: 这是它的几个例子,如下。

StringBuffer insert(int index, String str)StringBuffer insert(int index, char ch)

这里, 索引 指定了字符串将被插入到调用的 StringBuffer 对象中的索引。

// Java Program to Illustrate StringBuffer class// via insert() method // Importing required I/O classesimport java.io.*; // Main classclass GFG {     // Main driver method    public static void main(String[] args)    {        // Creating an object of StringBuffer class        StringBuffer s = new StringBuffer("GeeksGeeks");         // Inserting element and position as an arguments        s.insert(5, "for");        // Returns GeeksforGeeks        System.out.println(s);         s.insert(0, 5);        // Returns 5GeeksforGeeks        System.out.println(s);         s.insert(3, true);        // Returns 5GetrueeksforGeeks        System.out.println(s);         s.insert(5, 41.35d);        // Returns 5Getr41.35ueeksforGeeks        System.out.println(s);         s.insert(8, 41.35f);        // Returns 5Getr41.41.3535ueeksforGeeks        System.out.println(s);         // Declaring and initializing character array        char geeks_arr[] = { 'p', 'a', 'w', 'a', 'n' };         // Inserting character array at offset 9        s.insert(2, geeks_arr);        // Returns 5Gpawanetr41.41.3535ueeksforGeeks        System.out.println(s);    }}

输出

GeeksforGeeks5GeeksforGeeks5GetrueeksforGeeks5Getr41.35ueeksforGeeks5Getr41.41.3535ueeksforGeeks5Gpawanetr41.41.3535ueeksforGeeks

例4:reverse( )

它可以使用 reverse( ) 对StringBuffer对象内的字符进行反转 。 该方法返回它所调用的反转对象。

// Java Program to Illustrate StringBuffer class// via reverse() method // Importing I/O classesimport java.io.*; // Main classclass GFG {     // Main driver method    public static void main(String[] args)    {        // Creating a string via creating        // object of StringBuffer class        StringBuffer s = new StringBuffer("GeeksGeeks");         // Invoking reverse() method        s.reverse();         // Returns "skeeGrofskeeG"        System.out.println(s);    }}

输出

skeeGskeeG

例5: delete()和deleteCharAt( )

通过使用 delete()deleteCharAt() 方法,可以删除StringBuffer中的字符。 delete() 方法从调用对象中删除一串字符。这里,start Index指定了要删除的第一个字符的索引,end Index指定了要删除的最后一个字符之后的一个索引。因此,删除的子串从start Index到endIndex-1。结果是StringBuffer对象被返回。 deleteCharAt( ) 方法在loc指定的索引处删除字符。它返回结果的StringBuffer对象。

语法

StringBuffer delete(int startIndex, int endIndex)StringBuffer deleteCharAt(int loc)
// Java Program to Illustrate StringBuffer class// via delete() and deleteCharAt() Methods // Importing I/O classesimport java.io.*; // Main classclass GFG {     // Main driver method    public static void main(String[] args)    {        StringBuffer s = new StringBuffer("GeeksforGeeks");         s.delete(0, 5);        // Returns forGeeks        System.out.println(s);         s.deleteCharAt(7);        // Returns forGeek        System.out.println(s);    }}

输出

forGeeksforGeek

例6: replace( )

它可以通过调用replace( )将StringBuffer对象中的一组字符替换成另一组字符。被替换的子串是由startIndex和endIndex指定的。因此,从start Index到endIndex-1的子串被替换。替换的字符串以str的形式传递。得到的StringBuffer对象被返回。

语法

StringBuffer replace(int startIndex, int endIndex, String str)

例子

// Java Program to Illustrate StringBuffer class// via replace() method // Importing I/O classesimport java.io.*; // Main classclass GFG {     // Main driver method    public static void main(String[] args)    {        StringBuffer s = new StringBuffer("GeeksforGeeks");        s.replace(5, 8, "are");         // Returns GeeksareGeeks        System.out.println(s);    }}

输出

GeeksareGeeks

相关推荐