当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。