1.StringBuilder概述
StringBuilder是一个可变的字符串类,我们可以把它看成一个容器
(可变指的是StringBuilder对象中的内容是可变的。)
StringBuilder在Java.lang包下,故使用时不需要导包。
String和StringBuilder的区别:
String:内容是可变的StringBuilder:内容是不可变的
2.StringBuilder构造方法:
public StringBuilder();创建一个空白可变字符串对象,不含有任何内容public StringBuilder(String str);根据字符串的内容,来创建可变字符串对象
public class StringBuilderDemo1 {public static void main(String[] args) {//public StringBuilder();创建一个空白可变字符串对象,不含有任何内容StringBuilder s = new StringBuilder();System.out.println("s:" +s);System.out.println("s.length():"+s.length());//public StringBuilder(String str);根据字符串的内容,来创建可变字符串对象StringBuilder s2 = new StringBuilder("hello");System.out.println("s2:" +s2);System.out.println("s2.length():"+s2.length());}}
3.StringBuilder的添加和反转方法
public StringBuilder append(任意类型):添加数据,并返回对象本身public StringBuilder reverse():返回相反的字符序列
案例一:
public class StringBuilderDemo2 {public static void main(String[] args) {//创建对象StringBuilder s = new StringBuilder();//public StringBuilder append(任意类型):添加数据,并返回对象本身StringBuilder s2 = s.append("hello");System.out.println("s:"+s);System.out.println("s2:"+s2);System.out.println(s == s2); }}
运行结果:s:hellos2:hellotrue
案例二:
public class StringBuilderDemo2 {public static void main(String[] args) {//创建对象StringBuilder s = new StringBuilder();//public StringBuilder append(任意类型):添加数据,并返回对象本身 //简化:不需要重新创建对象s.append("hello");s.append("world");s.append("java");s.append(100);System.out.println("s:"+s); }}
运行结果:s:helloworldjava100
案例三:
public class StringBuilderDemo2 {public static void main(String[] args) {//创建对象StringBuilder s = new StringBuilder();//再次简化:链式编程(因为调完方法还是返回对象本身,因此可以使用链式编程)s.append("hello").append("world").append("java").append(100);System.out.println("s:" +s); }}
运行结果:s:helloworldjava100
案例四:
public class StringBuilderDemo2 {public static void main(String[] args) {//创建对象StringBuilder s = new StringBuilder(); //再次简化:链式编程(因为调完方法还是返回对象本身,因此可以使用链式编程)s.append("hello").append("world").append("java").append(100);System.out.println("s:" +s); //public StringBuilder reverse():返回相反的字符序列s.reverse();System.out.println("s:" +s); }}
运行结果:s:helloworldjava100s:001avajdlrowolleh
4.StringBuilder和String相互转换
StringBuilder转换为String
public String toString():通过toString()就可以实现把StringBuilder转换为String
代码如下:
public class StringBuilderDemo3 {public static void main(String[] args) {//StringBuilder转换为StringStringBuilder s = new StringBuilder();s.append("hello");//String s1 = s;//这个是错误做法//public String toString():通过toString()就可以实现把StringBuilder转换为StringString s1 = s.toString();System.out.println(s1);}}
String转换为StringBuilder
public StringBuilder(String s):通过构造方法就可以实现把String转换为StringBuilder
代码如下:
public class StringBuilderDemo4 {public static void main(String[] args) {//String转换为StringBuilderString s = "hello";//StringBuilder s1 = s;//这个是错误的做法StringBuilder s1 = new StringBuilder(s);System.out.println(s1);}}