Java 字符串 join()
方法返回一个用给定分隔符连接的字符串。更多Java字符串拼接方法请参考这里 。
语法
join() 方法的语法如下:
public static String join(CharSequence delimiter, CharSequence... elements)
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
参数
- delimiter : 分隔符
- elements : 字符串
返回值
带分隔符的连接字符串
异常抛出
NullPointerException 如果元素或分隔符为空。
版本
jdk 1.8 开始
内部实现
// 类型 - 1
public static String join(CharSequence delimiter, CharSequence... elements)
{
Objects.requireNonNull(elements);
Objects.requireNonNull(delimiter);
StringJoiner jnr = new StringJoiner(delimiter);
for (CharSequence c: elements)
{
jnr.add(c);
}
return jnr.toString();
}
// 类型 - 2
public static String join(CharSequence delimiter, CharSequence... elements)
{
Objects.requireNonNull(elements);
Objects.requireNonNull(delimiter);
StringJoiner jnr = new StringJoiner(delimiter);
for (CharSequence c: elements)
{
jnr.add(c);
}
return jnr.toString();
}
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
{
Objects.requireNonNull(elements);
Objects.requireNonNull(delimiter);
StringJoiner jnr = new StringJoiner(delimiter);
for (CharSequence c: elements)
{
joiner.add(c);
}
return jnr.toString();
}
方法示例1
文件名: StringJoinExample.java
public class StringJoinExample{
public static void main(String args[]){
String joinString1=String.join("-","welcome","to","yxjc123");
System.out.println(joinString1);
}
}
输出:
welcome-to-yxjc123
方法示例2
使用分隔符,格式化日期值。
文件名: StringJoinExample2.java
public class StringJoinExample2 {
public static void main(String[] args) {
String date = String.join("-","2023","05","23");
System.out.print(date);
String time = String.join(":", "12","10","10");
System.out.println(" "+time);
}
}
输出:
2023-05-23 12:10:10
方法示例3
null异常的例子。
文件名: StringJoinExample3.java
public class StringJoinExample3
{
// 主要方法
public static void main(String argvs[])
{
String str = null;
str = String.join(null, "abc", "bcd", "apple");
System.out.println(str);
}
}
输出:
Exception in thread "main" java.lang.NullPointerException
at java.base/java.util.Objects.requireNonNull(Objects.java:221)
at java.base/java.lang.String.join(String.java:2393)
at StringJoinExample3.main(StringJoinExample3.java:7)
at java.base/java.util.Objects.requireNonNull(Objects.java:221)
at java.base/java.lang.String.join(String.java:2393)
at StringJoinExample3.main(StringJoinExample3.java:7)