Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an array as argument for string.Format()

Tags:

When trying to use an array as an argument for the string.Format() method, I get the following error:

FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

The code is as follows:

place = new int[] { 1, 2, 3, 4}; infoText.text = string.Format("Player1: {0} \n Player2: {1} \n Player3: {2} \n Player4: {3}", place); 

The Array contains four values and the arguments in the String.Format() are also the same.

What causes this error?

(The infoText.text is just a regular String object)

like image 885
martin36 Avatar asked Nov 30 '16 09:11

martin36


People also ask

How do I format an array of strings?

So how to convert String array to String in java. We can use Arrays. toString method that invoke the toString() method on individual elements and use StringBuilder to create String. We can also create our own method to convert String array to String if we have some specific format requirements.

What is string format () used for?

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.

What is return by format () method?

format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String. format() method, it uses the default locale by calling the Locale.

What is %s in string format?

The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value. The following Python code illustrates the way of performing string formatting.


2 Answers

You can convert int array to string array as pass it using System.Linq Select() extension method.

infoText.text = string.Format("Player1: {0} \nPlayer2: {1} \nPlayer3: {2} \nPlayer4: {3}",                                place.Select(x => x.ToString()).ToArray()); 

Edit:

In C# 6 and above, you can also able to use String Interpolation instead of using string.Format()

infoText.text = $"Player1: {place[0]}\nPlayer2: {place[1]} \nPlayer3: {place[2]} \nPlayer4: {place[3]}"; 

Check this fiddle for your reference.

like image 161
Balagurunathan Marimuthu Avatar answered Sep 20 '22 20:09

Balagurunathan Marimuthu


Quick fix.

var place = new object[] { 1, 2, 3, 4 }; 

C# does not support co-variant array conversion from int[] to object[] therefor whole array is considered as object, hence this overload with a single parameter is called.

like image 42
M.kazem Akhgary Avatar answered Sep 20 '22 20:09

M.kazem Akhgary