如何在 Java 中缓冲字符串

缓冲字符串是一种技术,系统在处理或打印出字符串之前,会将字符串的各部分临时存储在缓冲区中。以下是 Java 中缓冲字符串的不同方法 -

  • 使用 emit 方法进行字符串缓冲

  • 使用 StringBuffer 类

使用 emit 方法进行字符串缓冲

emit 方法将 字符串 的各部分收集到缓冲区中,并在达到一定长度后返回缓冲区。这减少了连续字符串连接造成的低效率。

示例

以下是使用 emit 方法进行字符串缓冲的示例 −

public class StringBuffer {
   public static void main(String[] args) {
      countTo_N_Improved();
   }
   private final static int MAX_LENGTH = 30;
   private static String buffer = "";
   private static void emit(String nextChunk) {
      if(buffer.length() + nextChunk.length() > MAX_LENGTH) {
         System.out.println(buffer);
         buffer = "";  
      }
      buffer += nextChunk;
   }
   private static final int N = 100;
   private static void countTo_N_Improved() {
      for (int count = 2; count <= N; count = count +2) {
         emit(" " + count);
      }
   }
}

输出

2 4 6 8 10 12 14 16 18 20 22
24 26 28 30 32 34 36 38 40 42
44 46 48 50 52 54 56 58 60 62
64 66 68 70 72 74 76 78 80 82

使用 StringBuffer 类

StringBuffer 是一个表示可变字符序列的类。它为不可变的 String 类提供了一种替代方案,使您能够更改字符串的内容,而不必每次都创建新对象。

示例

以下是使用 StringBuffer 类的示例 -

public class HelloWorld {
   public static void main(String []args) {
      StringBuffer sb = new StringBuffer("hello");
      sb.append("world");
      sb.insert(0, " Tutorialspoint");
      System.out.print(sb);
   }
}

输出

Tutorialspointhelloworld
java_strings.html