Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the size of an array when using String Split Method

I am trying to declare an array of size 3, then use the string split() method to assign values to each index of the array. However, the Split() method seems to override the size of the array and sets its size to the amount of substrings the Split() method comes out with.

So This is what I did,

string myString = "Hello world";
string[] myArray = new string[3];

for(int i = 0; i < 3; i++)
    myArray[i] = "";

myArray = myString.Split(' ');

But once again, when I use the Split() method, it overrides the size of my array and sets it to 2 which causes complications for me later on.

So I need to know how to use the split method to add strings into the array of size 3. If the array contains less than 3 items, I want to set the unassigned indexes to "" and if there are more than 3 substrings then I want to only take the first three and discard the rest.

Thanks in advance for any help guys.

like image 764
Restnom Avatar asked Apr 20 '26 11:04

Restnom


2 Answers

You can set the result of the string split to a new array, transferring the contents to the original array in a loop. If the string split array is longer than the original array then the original should be set to the new one in order to avoid an out of bounds exception.

var splitArray = myString.Split(' ');
if(splitArray.Length >= myArray.Length)
{
    myArray = splitArray;
}
else
{
    for(int i = 0; i < splitArray.Length; i++)
        myArray[i] = splitArray[i];
}
like image 143
Keiran Young Avatar answered Apr 23 '26 02:04

Keiran Young


Just needs a little re-jig (updated to cope with the case where the myArray is smaller than mySplitString):

string myString = "Hello world";
string[] mySplitString = myString.Split(' ');

string[] myArray = new string[3];
var loopLength = Math.min(mySplitString.length,myArray.length);

for(int i = 0; i < loopLength; i++){
    myArray[i] = mySplitString[i];
}
like image 21
Will Jenkins Avatar answered Apr 23 '26 02:04

Will Jenkins



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!