一、构造方法 public int capacity();//返回当前容量 public int length();//返回实际长度 public StringBuilder append(任意类型);//添加数据并且返回自身对象 public StringBuilder reverse();//实现字符串反转 二、String和StringBuilder的相互转换 StringBuilder-------》String 通过 public String toString();可以实现
StringBuilder sb=new StringBuilder(); sb.append("hello").append("world"); String s=sb.toString(); System.out.println(s);String--------》StringBuilder 通过构造方法,StringBuilder(String s)
String s="helloworld"; StringBuilder sb=new StringBuilder(s); System.out.println(sb);三、数组元素按格式拼接
思路:拼的时候用StringBuilder,拼完之后再转成String
public class StringBuilderTest { public static void main(String[] args) { int[] array= {1,2,3}; String s=arrayToString(array); System.out.println(s); } public static String arrayToString(int[] arr) { StringBuilder sb=new StringBuilder(); sb.append("[");//开始遍历之前加上【 for(int i=0;i<arr.length;i++) { if(i==arr.length-1) { sb.append(arr[i]);//如果是最后一个数字 }else{ sb.append(arr[i]).append(","); } } sb.append("]"); String result=sb.toString(); return result; } }四、实现字符串反转 String------>StringBuilder------->reverse()------>String
public class StringBuilderTest { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("输入字符串"); String str=sc.nextLine(); System.out.println(reverse(str)); } public static String reverse(String str) { StringBuilder sb=new StringBuilder(str); sb.reverse(); return sb.toString(); } }五、判断字符串是否对称 用到StringBuilder的反转函数,要把StringBuilder转换成tString
public class StringBuilderTest { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("输入字符串"); String str=sc.nextLine(); System.out.println(reverse(str)); } public static boolean reverse(String str) { StringBuilder sb=new StringBuilder(str); sb.reverse(); String result=sb.toString();//StringBuilder转换成tString return result.equals(str); } }