Java中的 StringJoiner toString() 方法
StringJoiner 的toString()用于将 StringJoiner 转换为 String。它返回当前值,由前缀、到目前为止添加的由分隔符分隔的值和后缀组成,除非没有添加任何元素,在这种情况下,返回前缀 + 后缀或空值字符
句法:
public String toString()
返回:此方法返回此 StringJoiner 的字符串表示形式
下面的程序说明了 toString() 方法:
示例 1:演示 toString() 与分隔符“”
Java
// Java program to demonstrate
// toString() method of StringJoiner
import java.util.StringJoiner;
public class GFG {
public static void main(String[] args)
{
// Creating StringJoiner with delimiter " "
StringJoiner str = new StringJoiner(" ");
// Adding elements in the StringJoiner
str.add("Geeks");
str.add("for");
str.add("Geeks");
// Print the StringJoiner
// using toString() method
System.out.println("StringJoiner: "
+ str.toString());
}
}
Java
// Java program to demonstrate
// toString() method of StringJoiner
import java.util.StringJoiner;
public class GFG {
public static void main(String[] args)
{
// Creating StringJoiner with delimiter ""
StringJoiner str = new StringJoiner(", ");
// Adding elements in the StringJoiner
str.add("Geeks");
str.add("for");
str.add("Geeks");
str.add("A");
str.add("Computer");
str.add("Portal");
// Print the StringJoiner
// using toString() method
System.out.println("StringJoiner: "
+ str.toString());
}
}
输出:
StringJoiner: Geeks for Geeks
示例 2:演示 toString() 与分隔符“,”
Java
// Java program to demonstrate
// toString() method of StringJoiner
import java.util.StringJoiner;
public class GFG {
public static void main(String[] args)
{
// Creating StringJoiner with delimiter ""
StringJoiner str = new StringJoiner(", ");
// Adding elements in the StringJoiner
str.add("Geeks");
str.add("for");
str.add("Geeks");
str.add("A");
str.add("Computer");
str.add("Portal");
// Print the StringJoiner
// using toString() method
System.out.println("StringJoiner: "
+ str.toString());
}
}
输出:
StringJoiner: Geeks, for, Geeks, A, Computer, Portal