string.Split忽略分隔符之间Null值 [英] string.Split ignores Null values between delimiters
问题描述
我想一些数据转换为与使用的StreamReader和StreamWriter的SQL语句。
我的问题是,当我分割线,其中2之间分隔符是什么,甚至没有一个空间,他们会被忽略,我也得到一个IndexOutOfRange误差
由于我temparray唯一无二至temparray [3],但它应该去喜欢temparray [6] ..
我怎么可以拆分并使用Null值或用简单的字符代替那些空值,所以,我没有得到我想要的IndexOutOfRange错误创建我的SQL语句?
的foreach(字符串值)
{
INT TEMP = 1 ;
的String [] = temparray a.Split(';');
streamWriter.WriteLine(插入到表丰资本值({0},{1},{2}),温度,temparray [1],temparray [4]);
临时++;
}
首先,这是引狼入室( SQL注入)。你应该的最起码的逃避字符串进行解析的值。
和你似乎是错误的,因为String.Split究竟是干什么的你想用默认的 的X; Y ;; Z.Split(';')
返回一个四元天线阵 {X,Y,,Z}
。您可以使用 StringSplitOptions.RemoveEmptyEntries
达到上述行为:X; Y ;; Z.Split(新[] {','} ,StringSplitOptions.RemoveEmptyEntries)
返回三的-element阵列 {X,Y,Z}
。这是你不想要的东西,就像你说的
无论哪种方式,Überarbeitung德SAV Seite;围兜;;;; PB;。 .Split(';')
这里返回七个元素的数组我,所以请检查您的投入和实施...
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++;
}
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…
这篇关于string.Split忽略分隔符之间Null值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!