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!
%s refers to a string data type, %f refers to a float data type, and %d refers to a double data type.
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.
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.
you can use
System.out.format("%s". Arrays.toString(your_array));
Java 8:
String formatted = Stream.of(arrayOfStrings)
.collect(Collectors.joining(",","[","]"));
String formatted = Stream.of(arrayOfSomethingElse)
.map(Object::toString)
.collect(Collectors.joining(",","[","]"));
Use a loop:
for (String s : array) {
System.out.print(String.format("%s ", s));
}
System.out.println();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With