由于引入了Java8 StringJoiner类,因此您可以构造由所需定界符分隔的字符序列。
序号 | 构造函数与说明 |
---|---|
1 | StringJoiner(CharSequence delimiter) 此构造函数创建一个空的(无字符)StringJoiner,仅带有指定定界符的副本。 |
2 | StringJoiner(CharSequence分隔符,CharSequence前缀,CharSequence后缀) 这将构造一个不带字符的StringJoiner。 |
add() -此方法接受一个CharacterSequence对象(Segment,String,StringBuffer,StringBuilder),并将其添加到当前Joiner中,在构造它时使用分隔符将下一个和上一个元素(如果有)分开。
import java.util.StringJoiner; public class StringJoinerExample { public static void main(String args[]) { StringJoiner joiner = new StringJoiner(" "); joiner.add("Hello"); joiner.add("how"); joiner.add("are"); joiner.add("you"); System.out.println(joiner); } }
Hello how are you
length() -此方法返回当前Joiner的长度,即其中包括分隔符的数字字符。
import java.util.StringJoiner; public class StringJoinerExample { public static void main(String args[]) { StringJoiner joiner = new StringJoiner(" "); joiner.add("Hello"); joiner.add("how"); joiner.add("are"); joiner.add("you"); System.out.println("Contents: "+joiner); System.out.println("length: "+joiner.length()); } }
Contents: Hello how are you length: 17
merge() -此方法接受一个StringJoiner对象,将其添加/连接到当前对象,然后返回生成的StringJoiner对象。
import java.util.StringJoiner; public class StringJoinerExample { public static void main(String args[]) { StringJoiner joiner1 = new StringJoiner(" "); joiner1.add("Hello"); joiner1.add("how"); joiner1.add("are"); joiner1.add("you"); StringJoiner joiner2 = new StringJoiner(" "); joiner2.add("Welcome"); joiner2.add("to"); joiner2.add("Nhooo"); StringJoiner result = joiner1.merge(joiner2); System.out.println("Contents: "+result); } }
Contents: Hello how are you Welcome to Nhooo
setEmptyValue() -此方法接受一个CharacterSequence对象作为参数,并将其设置为当前StringJoiner对象的空Sting值,即,如果没有元素添加到StringJoiner对象,则在打印其内容时使用此方法设置的值将显示。简而言之,一旦在StringJoiner对象上调用此方法,就永远不会将其视为空。
import java.util.StringJoiner; public class StringJoinerExample { public static void main(String args[]) { StringJoiner joiner = new StringJoiner(" "); joiner.setEmptyValue("sample empty value"); System.out.println(joiner); } }
sample empty value
toString() -此方法以Sting对象的形式返回当前StringJoiner的内容。
import java.util.StringJoiner; public class StringJoinerExample { public static void main(String args[]) { StringJoiner joiner = new StringJoiner(" "); joiner.add("Hello"); joiner.add("how"); joiner.add("are"); joiner.add("you"); String value = joiner.toString(); System.out.println(value); } }
Hello how are you