string.Split ignores Null values between delimiter

2019-07-04 12:07发布

I'm trying to convert some data into sql statements with the use of Streamreader and Streamwriter.

My problem is, when i split lines which in which between 2 delimiters is nothing, not even a space, they get ignored and i get a IndexOutOfRange error

because my temparray only goes till temparray[3] , but it should go to like temparray[6] ..

How can i split and use Null values or replace those null values with a simple char, so that i dont get an IndexOutOfRange error when i want to create my sql statements ?

foreach (string a in values)
{
    int temp = 1;
    String[] temparray = a.Split(';');
    streamWriter.WriteLine("Insert into table Firma values({0},'{1}','{2}')", temp, temparray[1], temparray[4]);
    temp++;
}

8条回答
够拽才男人
2楼-- · 2019-07-04 12:28

I don't see your issue occurring. The following outputs a string.Empty for string[2] and has all 5 elements

        string[] str = "0,1,,3,4".Split(new char[] { ',' });
        foreach (string s in str)
        {
            Debug.Print(s);
        }

output

0
1

3
4
查看更多
冷血范
3楼-- · 2019-07-04 12:37

First of all, this is asking for trouble (SQL injection). You should at the very least escape the values parsed from the string.

And you seem to be mistaken, as String.Split does exactly what you want by default: "x;y;;z".Split(';') returns a four-element array {"x", "y", "", "z"}. You can achieve the described behavior by using StringSplitOptions.RemoveEmptyEntries: "x;y;;z".Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries) returns a three-element array {"x", "y", "z"}. Which is what you do not want, as you say.

Either way, "Überarbeitung der SAV Seite;b.i.b.;;;;PB;".Split(';') returns a seven-element array here for me, so check your inputs and implementation…

查看更多
登录 后发表回答