Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a string array in java

I have a string array which has k elements. I want to print them out using System.out.format, but the issue is that I do not know k. So essentially, I want to use something like: System.out.format("%s %s ... k times", str1, str2, ... strk); (where k is a variable)

I was looking through the java documentation, but could not find a way to do this. Is there a simple way out?

Thanks!

like image 663
piedpiper Avatar asked Aug 20 '13 12:08

piedpiper


People also ask

What is %d and %s in java?

%s refers to a string data type, %f refers to a float data type, and %d refers to a double data type.

Can you format strings in java?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string.

Is string and string [] same in java?

String[] and String... are the same thing internally, i. e., an array of Strings. The difference is that when you use a varargs parameter ( String... ) you can call the method like: public void myMethod( String... foo ) { // do something // foo is an array (String[]) internally System.


3 Answers

you can use

System.out.format("%s". Arrays.toString(your_array));
like image 162
Ruchira Gayan Ranaweera Avatar answered Oct 30 '22 14:10

Ruchira Gayan Ranaweera


Java 8:

String formatted = Stream.of(arrayOfStrings)
    .collect(Collectors.joining(",","[","]"));

String formatted = Stream.of(arrayOfSomethingElse)
    .map(Object::toString)
    .collect(Collectors.joining(",","[","]"));
like image 43
Dominic Fox Avatar answered Oct 30 '22 16:10

Dominic Fox


Use a loop:

for (String s : array) {
    System.out.print(String.format("%s ", s));
}
System.out.println();
like image 22
duffymo Avatar answered Oct 30 '22 15:10

duffymo