概述
String Joiner跟String Builder一样,亦可以看成是一个容器,创建之后iu里面的内容是可变的
作用
提高字符串的操作效率,而且代码编写特别简洁,但是目前市场上很少有人用
JDK8
package stringdemo;
import java.util.StringJoiner;
public class StringJoinerDemo2 {
public static void main(String[] args) {
//1.创建对象
StringJoiner sj = new StringJoiner(",", "[", "]");
//2.添加元素
sj.add("aaa").add("bbb").add("ccc");
int len = sj.length();
System.out.println(len);//13 如果空格后面加空格,那么就是15
System.out.println(sj);
String str = sj.toString();
System.out.println(str);
}
}
小总结
package text6;
import java.util.Scanner;
import java.util.StringJoiner;
public class Luoma {
public static void main(String[] args) {
//键盘录入一个一个字符串
Scanner sc = new Scanner(System.in);
String str;
while (true) {
System.out.println("请输入一个字符串");
str = sc.next();
System.out.println(str);
//2.校验字符串是否满足规则
boolean flag = checkSter(str);
if (flag){
break;
}else{
System.out.println("输入的字符串里面只能是数字,请重新输入");
continue;
}
}
//将内容变成罗马数字
//查表法
StringJoiner sj = new StringJoiner("-");
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int number = c - 48;
String s = changLuoMa(number);
sj.add(s);
sj.toString();
}
System.out.println(sj);
}
public static String changLuoMa(int number){
String[] arr = {"","Ⅰ","Ⅱ","Ⅲ","Ⅳ","Ⅴ","Ⅵ","Ⅶ","Ⅷ","Ⅸ"};
return arr[number];
}
public static boolean checkSter(String str){
//1.长度小于等于九
if (str.length()>9){
return false;
}
//2.只能是数字
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c < '0' || c > '9'){
return false;
}
}
return true;
}
}