📜  Java中的StringJoiner length()方法

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

Java中的StringJoiner length()方法

StringJoiner 的length()用于找出 StringJoiner 的长度(以字符为单位)。它返回此 StringJoiner 的字符串表示形式的长度。请注意,如果未调用任何 add 方法,则将返回字符串表示的长度(前缀 + 后缀或空值)。该值应等同于 toString().length()。
句法:

public int length()

返回:该方法返回StringJoiner当前值的长度
下面的程序说明了 length() 方法:
示例 1:演示带有分隔符“”的 length()

Java
// Java program to demonstrate
// length() 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
        System.out.println("StringJoiner: "
                           + str.toString());
 
        // Printing the length of str
        // using length() method
        System.out.println(str.length());
    }
}


Java
// Java program to demonstrate
// length() 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
        System.out.println("StringJoiner: "
                           + str.toString());
 
        // Printing the length of str
        // using length() method
        System.out.println(str.length());
    }
}


输出:
StringJoiner: Geeks for Geeks
15

示例 2:使用分隔符“,”来演示 length()

Java

// Java program to demonstrate
// length() 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
        System.out.println("StringJoiner: "
                           + str.toString());
 
        // Printing the length of str
        // using length() method
        System.out.println(str.length());
    }
}
输出:
StringJoiner: Geeks, for, Geeks, A, Computer, Portal
38