當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java StringJoiner length()用法及代碼示例


StringJoiner的length()用於查找StringJoiner的長度(以字符為單位)。它返回此StringJoiner的String表示形式的長度。請注意,如果未調用任何add方法,則將返回String表示形式的長度(前綴+後綴或emptyValue)。該值應等於toString().length()。

用法:

public int length()

返回值:此方法返回StringJoiner當前值的長度


以下示例程序旨在說明length()方法:

示例1:用分度符“”演示length()

// Java program to demonstrate 
// length() method of StringJoiner 
  
import java.util.StringJoiner; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Creating StringJoiner with delimeter " " 
        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()); 
    } 
}
輸出:
StringJoiner: Geeks for Geeks
15

示例2:演示帶有分隔符“,”的length()

// Java program to demonstrate 
// length() method of StringJoiner 
  
import java.util.StringJoiner; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Creating StringJoiner with delimeter "" 
        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


相關用法


注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 StringJoiner length() method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。