String Buffer to String Builder

时间:2017-02-19 19:05:34

标签: java

如何将String Buffer的函数转换为String Builder。我知道这两者非常相似但我无法将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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

你应该使用StringBuffer和StringBuilder与你提供的代码完全相同的输出。

StringBuffer和StringBuilder之间的区别在于StringBuffer似乎过于杀伤,因为它是线程安全的。

如果您收到错误,可能与以下内容有关:

  • 主题问题
  • 未正确设置开发环境
  • 错别字
  • 文件格式(有时您从具有不可见字符的源中复制/粘贴代码,阻止您正确编译文件)。

根据我在评论中看到的内容,您的行或字符的隐藏末尾不符合您平台的正确编码。