拆分字符串并放入DataTable,找到第二个索引号

时间:2012-12-13 15:59:07

标签: c# string indexing split

我有一个关于拆分字符串的问题,并把它放在DataTable中。我怎么知道第二个数组是字符串还是数字?

我有一个包含许多字符串的文字:

 text : ...
        abc 123 def 1 \"ok lo\" ;
        abc def 1 \"ok lo\" ;
        ...

数组2:

 tmpList[0] = abc
 tmpList[1] = 123
 tmpList[2] = def
 tmpList[3] = 1 \"ok lo\"

ARRAY1:

 tmpList[0] = abc
 tmpList[1] = def
 tmpList[2] = 1 \"ok lo\

要查找abc的所有字符串,请执行以下操作:

        StreamReader fin = new StreamReader(userSelectedFilePath1);
        string tmp = "";
        while ((tmp = fin.ReadLine()) != null)
        {
        if (tmp.StartsWith("abc "))
            {
              var tmpList1 = tmp.Split(new[] { '"' }).SelectMany((s, i) =>
                {
                    if (i % 2 == 1) return new[] { s };
                    return s.Split(new[] { ' ', ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
                }).ToList();

                 table.Rows.Add(new object[] { tmpList1[0], tmpList1[1], tmpList1[2], tmpList1[3]}); 

            }

        }

使用此代码,我可以找到String startswith abc,split并放入DataTable。我怎么知道第二个索引是字符串还是int?与我所做的一样,我有第二个索引的错误,并且它不正确地分裂。我认为if(tmp.StartsWith(abc NUMBER?)) else执行上面的代码

1 个答案:

答案 0 :(得分:0)

当您执行String.Split()时,数组中的所有值也将是字符串,因此在您的ABC示例中:

tmpList[1] = 123 // this is incorrect as the value is an int

这应该是:

tmpList[1] = "123" // value is a string

然后你可以做的是尝试将值转换为int,如果失败,你知道它不是int:

int number;
bool result = Int32.TryParse(tmpList[1], out number);
if (result) {
    // your code for if the value is a number        
}
else {
    // your code for if the value is not a number
}

here复制代码示例。