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)
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.
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.
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.
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.
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.
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.
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