📜  Java String join() 示例

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

Java String join() 示例

Java.lang。 字符串.join()方法将给定的元素与分隔符连接起来,并返回连接后的字符串。注意,如果元素为 null,则添加 null。join ()方法从 JDK 1.8 开始包含在Java字符串中。
Java 字符串中有两种类型的join()方法。
句法:

public static String join(CharSequence deli, CharSequence... ele)  
and  
public static String join
(CharSequence deli, Iterable ele)     
Parameters:
deli- delimiter to be attached with each element 
ele- string or char to be attached with delimiter
Returns :  string joined with delimiter.
// Java program to demonstrate
// working of join() method
  
class Gfg1 {
    public static void main(String args[])
    {
        // delimiter is "<" and elements are "Four", "Five", "Six", "Seven"
        String gfg1 = String.join(" < ", "Four", "Five", "Six", "Seven");
  
        System.out.println(gfg1);
    }
}

输出:

Four < Five < Six < Seven
// Java program to demonstrate
// working of join() method
  
class Gfg2 {
    public static void main(String args[])
    {
        // delimiter is "  " and elements are "My",
        // "name", "is", "Niraj", "Pandey"
        String gfg2 = String.join("  ", "My", "name", "is", "Niraj", "Pandey");
  
        System.out.println(gfg2);
    }
}

输出:

My name is Niraj Pandey
// Java program to demonstrate
// working of join() method
  
class Gfg3 {
    public static void main(String args[])
    {
        // delimiter is "->" and elements are "Wake up", 
        // "Eat", "Play", "Sleep", "Wake up"
  
        String gfg3 = String.join("-> ", "Wake up", "Eat",
                      "Play", "Sleep", "Wake up");
  
        System.out.println(gfg3);
    }
}

输出:

Wake up-> Eat-> Play-> Sleep-> Wake up