String Builder
1.定义:一种比String更灵活,长度可变的字符串类
2.构造方法
package com.ljh.StringBuilderDemo;
/**
* @Author: ljh
* @Date: 2022/1/8 21:24
* @Description:
*/
public class StringBuilderDemo {
public static void main(String[] args) {
//构造方法,无参构造方法,长度为0
StringBuilder stringBuilder = new StringBuilder();
System.out.println(stringBuilder.length());//0
//有参构造方法
StringBuilder stringBuilder1 = new StringBuilder("hello !");
System.out.println(stringBuilder1.length());//7(空格算字符)
}
}
3.常用方法
package com.ljh.StringBuilderDemo;
/**
* @Author: ljh
* @Date: 2022/1/8 21:24
* @Description:
*/
public class StringBuilderDemo {
public static void main(String[] args) {
StringBuilder stringBuilder = new StringBuilder();
//添加方法
stringBuilder.append("hello");
stringBuilder.append("world");
System.out.println(stringBuilder);//helloworld
//该方法使用时返回其自身,因此可以链式编程
stringBuilder.append("for").append("world");
System.out.println(stringBuilder);//helloworldforworld
//倒序字符串
stringBuilder.reverse();
System.out.println(stringBuilder);//dlrowrofdlrowolleh
}
}
4.String和StringBuilder的转换
package com.ljh.StringBuilderDemo;
/**
* @Author: ljh
* @Date: 2022/1/8 21:24
* @Description:
*/
public class StringBuilderDemo {
public static void main(String[] args) {
//1.把StringBuilder转为String用toString()方法
StringBuilder stringBuilder = new StringBuilder();
//添加方法
stringBuilder.append("hello");
String s = stringBuilder.toString();
System.out.println(s);//hello
//2.把String转为StringBuilder用构造方法
String s1 ="233";
StringBuilder stringBuilder1 = new StringBuilder(s1);
System.out.println(stringBuilder1);//233
}
}
5.练习
需求:定义一个方法,把int数组中的数据按照指定的格式拼接成一个字符串返回,调用该方法,并在控制台
输出结果。例如,数组为int[ arr= {1,2,3};, 执行方法后的输出结果为: [1,2, 3]
package com.ljh.StringBuilderDemo;
/**
* @Author: ljh
* @Date: 2022/1/9 16:00
* @Description: 练习1
*/
public class StringBuilderDemo02 {
public static void main(String[] args) {
int[] arr = {1,2,3};
System.out.println(show(arr));
}
public static String show(int[] ints){
StringBuilder stringBuilder = new StringBuilder("[");
for (int i=0;i<ints.length;i++){
if (i==ints.length-1){
stringBuilder.append(ints[i]);
}
else{
stringBuilder.append(ints[i]).append(",");
}
}
stringBuilder.append("]");
return stringBuilder.toString();
}
}
需求:定义一个方法,实现字符串反转。键盘录入一个字符串,调用该方法后,在控制台输出结果
例如,键盘录入abc,输出结果cba
package com.ljh.StringBuilderDemo;
import java.util.Scanner;
/**
* @Author: ljh
* @Date: 2022/1/9 16:11
* @Description:练习2
*/
public class StringBuilderDemo03 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
System.out.println(getString(s));
scanner.close();
}
public static String getString(String s){
StringBuilder stringBuilder = new StringBuilder(s);
stringBuilder.reverse();
return stringBuilder.toString();
}
}