Home > OS >  How to split string and store in array [closed]
How to split string and store in array [closed]

Time:10-08

Need to spilt, remove and store the string in array, My string 9_31_EI1111011111

Already tried using this code but getting the error

Index was outside the bounds of the array

string[] str_doc = el.Value.Remove(0,19).Split('_', '.');
service_code = str_doc[0].ToString();
strDocNumber = str_doc[1].ToString();

I want to store service_code = 31 and strDocNumber = EI1111011111

CodePudding user response:

Example with using Linq (using System.Linq;):

string[] str_doc = el.Value.Split('_').Skip(1).ToArray();
service_code = str_doc[0]
strDocNumber = str_doc[1]

After the Split('_') you will get an array of length 3. Because you want to delete the first item you can use the Skip(..) function (Linq is required). Skip(1) will skip the first element in the array and returns an Enumerable<SkipIterator> but what we need here is an array, therefore just use the toArray() method to get a string[].

CodePudding user response:

The code you are using for the split is fine; though you should be using str_doc[1] and str_doc[2] for the values you want. Note that for this to work always, every found xml element el would need to have at least 2 splits ('_' or '.'). Otherwise, some sort of validation would be required.

Your problem is coming from either el.Value.Remove(0,19) or that missing validation. It could be that you have the wrong element, that you are removing too much of the value or that the value does not contain enough splits.

I would suggest debugging this by temporarily removing the split code and printing the value of the element both before and after applying Remove(0,19).

  • Related