java - 字符串缓冲区到字符串生成器

标签 java

<分区>

您如何将字符串缓冲区的功能转换为字符串生成器。我知道这两者非常相似,但我无法将 StringBuffer sb = new StringBuffer(); 更改为 StringBuilder sb = new StringBuilder();错误信息。

这是我编写的一些代码:

StringBuffer sb = new StringBuffer();      //Create a new String Buffer with nothing in it
for (int n = 0; n < 1; n++) {
   sb.append("Billy ");                //Add  (first name) 
   sb.append("Scranner");              //Add  (surname)
   System.out.println(sb);             //Print the string buffer
   sb.insert(5," D");                  //Insert  " D" at the 4th character
   System.out.println(sb);             //Print the String Buffer with the middle initial
   sb.delete(5, 7);                    //Delete the character line from 4 to 6  
   sb.reverse();                       //Reverse the String Buffer 
   System.out.println(sb);             //Print the reversed String Builder

如果我的问题看起来不清楚,我深表歉意,TLDR;我想知道如何使用 String Builder 而不是 String Buffer 获得与该程序相同的输出。

程序输出如下:

Billy Scranner

Billy D Scranner

rennarcS ylliB

编辑:这是我用 Builder 替换 Buffer 时得到的输出:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
     The method append(String) is undefined for the type StringBuilder
     The method append(String) is undefined for the type StringBuilder
     The method insert(int, String) is undefined for the type StringBuilder
     The method delete(int, int) is undefined for the type StringBuilder
     The method reverse() is undefined for the type StringBuilder

最佳答案

StringBuffer sb = new StringBuffer(); 替换为 StringBuilder sb = new StringBuilder(); 没有错误

    import java.lang.StringBuilder;

    StringBuilder sb = new StringBuilder();
    sb.append("Billy "); 
    sb.append("Scranner"); 
    System.out.println(sb); 

    sb.insert(5, " D");
    System.out.println(sb); 
    sb.delete(5, 7);

    sb.reverse(); 

    System.out.println(sb);

输出:

Billy Scranner
Billy D Scranner
rennarcS ylliB

关于java - 字符串缓冲区到字符串生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42331546/

相关文章:

java - 如何使用 Character.toUpperCase?

java - 如何通过读取 bufferedreader 来获取上一行的可变数量

java - 如何在命令提示符中创建特定命令的快捷方式?

使用 JSONParser 的 java.lang.NullpointerException

Java继承,使用super()

java - 退出 Action 监听器

java - 编译 Play 2.x - Java 应用程序超时(15 分钟)| Heroku 和 Play 框架

java - 如何以编程方式查找对某个方法的所有引用?

java - 递归半等字符串

java - context.lookup ("datasource")返回 org.jboss.jca.adapters.jdbc.WrapperDataSource