Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the shortest way to init a string array with empty strings?

Tags:

arrays

string

c#

Surprisingly for me

new string[count];

is filled with nulls. So I came up with

var emptyStrings = Enumerable.Range(0, count)
    .Select(a => String.Empty)
    .ToArray();

which is very verbose. Isn't there a shorcut?

like image 885
Jader Dias Avatar asked Nov 24 '10 15:11

Jader Dias


People also ask

How do you initialize an empty string array?

Create an array of empty strings that is the same size as an existing array. It is a common pattern to combine the previous two lines of code into a single line: str = strings(size(A)); You can use strings to preallocate the space required for a large string array.

How do you initialize a string array?

Initialization of Arrays of Strings: Arrays can be initialized after the declaration. It is not necessary to declare and initialize at the same time using the new keyword. However, Initializing an Array after the declaration, it must be initialized with the new keyword. It can't be initialized by only assigning values.

How do you create an empty string array in Java?

So in your code, you can use: private static final String[] EMPTY_ARRAY = new String[0];

How do I create an empty string array in typescript?

To declare an empty array for a type variable, set the array's type to Type[] , e.g. const arr: Animal[] = [] . Any elements you add to the array need to conform to the specific type, otherwise you would get an error. Copied!


1 Answers

You can use Enumerable.Repeat:

 string[] strings = Enumerable.Repeat(string.Empty, count).ToArray();

(But be aware that creating a string array of the correct size and looping will give better performance.)

like image 86
Mark Byers Avatar answered Oct 06 '22 00:10

Mark Byers