Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert blank strings into array based on index

Tags:

arrays

c#

Let's say I have an array for example

string[] A = {"1","2","3","4","5"}

I want the array to be of size 10, and want to insert blank strings after a certain index.

For example, I could make it size 10 and insert strings after index 3 which would result in

A = {"1","2","3","4","","","","","","5"}

Basically the elements after the given index will be pushed to the end and blank strings will take the empty space in between.

This is what I tried but it only adds one string and doesnt exactly set a size for the array

var foos = new List<string>(A);
foos.Insert(33, "");
foos[32] = "";
A = foos.ToArray();
like image 277
sparta93 Avatar asked Jul 13 '26 22:07

sparta93


1 Answers

You can use InsertRange

var l = new List<string>{"1","2","3","4","5"};
l.InsertRange(3, new string[10 - l.Count]);
foreach(var i in l)
    Console.WriteLine(i);

Note: The above doesn't populate with empty strings but null values, but you can easily modify the new string[] being used to be populated with your desired default.

For example; see How to populate/instantiate a C# array with a single value?

like image 90
Sayse Avatar answered Jul 16 '26 11:07

Sayse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!