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


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


StringJoiner的toString()用於將StringJoiner轉換為String。它返回當前值,包括前綴,到目前為止添加的值(由定界符分隔)和後綴,除非在這種情況下未添加任何元素,則返回前綴+後綴或emptyValue字符

用法:

public String toString()

返回值:此方法返回此StringJoiner的字符串表示形式


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

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

// Java program to demonstrate 
// toString() 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 
        // using toString() method 
        System.out.println("StringJoiner: "
                           + str.toString()); 
    } 
}
輸出:
StringJoiner: Geeks for Geeks

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

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


相關用法


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