📜  Java中的 StringJoiner add() 方法

📅  最后修改于: 2022-05-13 01:55:03.742000             🧑  作者: Mango

Java中的 StringJoiner add() 方法

StringJoiner 的add(CharSequence newElement)将给定 CharSequence 值的副本添加为 StringJoiner 值的下一个元素。如果 newElement 为 null,则添加“null”。
句法:

public StringJoiner add(CharSequence newElement)

参数:此方法需要一个强制参数newElement ,它是要添加的元素。
返回:此方法返回对此 StringJoiner 的引用
下面的程序说明了 add() 方法:
示例 1:演示带分隔符“”的 add()

Java
// Java program to demonstrate
// add() method of StringJoiner
 
import java.util.StringJoiner;
 
public class GFG1 {
    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
        System.out.println(str.toString());
    }
}


Java
// Java program to demonstrate
// add() method of StringJoiner
 
import java.util.StringJoiner;
 
public class GFG1 {
    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
        System.out.println(str.toString());
    }
}


输出:
Geeks for Geeks

示例 2:演示带有分隔符“,”的 add()

Java

// Java program to demonstrate
// add() method of StringJoiner
 
import java.util.StringJoiner;
 
public class GFG1 {
    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
        System.out.println(str.toString());
    }
}
输出:
Geeks,for,Geeks