字符串创建
//1.String()
String str = new String();
//2.String(char[] a)
char[] a = {'a','b','c','d'};
String str = new String(a);
//3.String(char[] a, int offset, int length)
char[] a = {'a','b','c','d'}
String str = new String(a, 1, 2);
Java8中的字符串连接
Collectors.joining
在JDK8中,可以采用函数式编程(使用 Collectors.joining 收集器)的方式对字符串进行更优雅的连接。
Collectors.joining 收集器 支持灵活的参数配置,可以指定字符串连接时的 分隔符,前缀 和 后缀 字符串。
// 定义人名数组
final String[] names = {"Zebe", "Hebe", "Mary", "July", "David"};
Stream<String> stream1 = Stream.of(names);
Stream<String> stream2 = Stream.of(names);
Stream<String> stream3 = Stream.of(names);
// 拼接成 [x, y, z] 形式
String result1 = stream1.collect(Collectors.joining(", ", "[", "]"));
// 拼接成 x | y | z 形式
String result2 = stream2.collect(Collectors.joining(" | ", "", ""));
// 拼接成 x -> y -> z] 形式
String result3 = stream3.collect(Collectors.joining(" -> ", "", ""));
System.out.println(result1);
System.out.println(result2);
System.out.println(result3);
程序输出结果如下:
[Zebe, Hebe, Mary, July, David]
Zebe | Hebe | Mary | July | David
Zebe -> Hebe -> Mary -> July -> David
StringJoiner
List<String> list = Arrays.asList("a", "b", "c", "d", "e", "f", "g");
StringJoiner result = new StringJoiner(delimiter);
for (String str : list) {
result.add(str);
}
System.out.println(result.toString());
程序输出结果如下:
a, b, c, d, e, f, g
String.join
JDK1.8 为 String 类添加了一个新的静态方法,String.join
List<String> list = Arrays.asList("a", "b", "c", "d", "e", "f", "g");
String delimiter = ",";
String result = String.join(delimiter, list);
System.out.println(result);
String.join 方法的功能内部是通过 StringJoiner 来实现的,String.join (CharSequence, Iterable) 的源码:
public static String join(CharSequence delimiter,
Iterable<? extends CharSequence> elements) {
Objects.requireNonNull(delimiter) ;
Objects.requireNonNull(elements) ;
StringJoiner joiner = new StringJoiner(delimiter);
for(CharSequence cs : elements){
joiner.add(cs);
}
return joiner.toString();
}
StringJoiner 除了指定 分隔符 的构造方法,还有一个可以指定 分隔符、前缀和后缀 的构造方法:
StringJoiner(CharSequence delimiter)
StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
示例
List<String> list = Arrays.asList("a", "b", "c", "d", "e", "f", "g");
StringJoiner result = new StringJoiner(delimiter, "{", "}");
for (String str : list) {
result.add(str);
}
System.out.println(result.toString());
程序输出结果如下:
{a, b, c, d, e, f, g}