String和StringBuilder
3.1 StringBuilder概述StringBuilder是一个可变的字符串类,我们可以把它看成是一个容器这里的可变指的是StringBuilder对象中的内容是可变的String和StringBuilder的区别:String:内容是不可变的StringBuilder:内容是可变的public static void main(String[] args) {StringBuilder s
·
字符串
String和StringBuilder
3.1 StringBuilder概述
StringBuilder是一个可变的字符串类
,我们可以把它看成是一个容器这里的可变指的是StringBuilder对象中的内容是可变的
String和StringBuilder的区别:
String:内容是不可变的
StringBuilder:内容是可变的
public static void main(String[] args) {
StringBuilder s = new StringBuilder();
System.out.println("s:"+s);
System.out.println("s.length"+s.length());
StringBuilder sd = new StringBuilder("hello");
System.out.println("sd:"+sd);
System.out.println("sd.length:"+sd.length());
}
StringBuilder中的方法:
练习:字符串的拼接,反转
import java.sql.SQLOutput;
public class StringBuilderDemo01 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
// StringBuilder s1 = sb.append("hello");
// System.out.println("s1:"+s1);
// System.out.println("sb:"+sb);
// System.out.println(sb==s1); //存储地址相同
//
// sb.append("I ");
// sb.append("live ");
// sb.append("java");
// System.out.println(sb);
//链式编程
sb.append("I ").append("love ").append("java").append(100);
System.out.println("sb:"+sb);
//reverse():返回相反的字符序列
sb.reverse();
System.out.println("反转后的sb:"+sb);
}
}
public class StringBuilderDemo02 {
public static void main(String[] args) {
/*
//StringBuilder转换为String
StringBuilder sb =new StringBuilder();
sb.append("hello");
String s=sb.toString(); //通过toString()可以实现把StringBuilder转化为String
System.out.println(s);
*/
String s = "hello";
//通过构造的方法就可以实现把String转化为StringBuilder
StringBuilder sb = new StringBuilder(s);
System.out.println(sb);
}
}
StringBuilder的应用
字符串的拼接(升级版)
public class StringBuilderTest01 {
public static void main(String[] args) {
int[] a = {1, 2, 3};
String s = arrayToSting(a);
System.out.println("s:"+s);
}
public static String arrayToSting(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]).append(", ");
}
else{
sb.append(arr[i]);
}
}
sb.append("]");
String s = sb.toString(); //把结果转化为String
return s;
}
}
字符串的反转(升级版)(StringBuilder)
从接盘上获取一个字符串,用StringBuilder中的Reverse()的方法把字符串反转
思路:
先把String转化为StringBuilder
然后用StringBuilder中的反转方法Reverse()
最后把StringBuilder转化为String
import java.util.Scanner;
public class StringBuilderDemo03 {
public static void main(String[] args) {
System.out.println("请输入一个字符串");
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
String reverse = Reverse(s);
System.out.println(reverse);
}
public static String Reverse(String s) {
// StringBuilder sb = new StringBuilder(s); //String转化为StringBuilder
// StringBuilder reverse = sb.reverse(); //反转
// String s2 = reverse.toString(); //StringBuilder转化为String
// return s2;
return new StringBuilder(s).reverse().toString();
}
}
更多推荐
已为社区贡献11条内容
所有评论(0)