开发者

Splitting a string by \t - will successive tabs cause issues?

I'm writing an automation program to parse a tab-delimited file and write the data into another program. Currently it takes each line of the file, splits it by tab, and uses the different entries in it's commands. My issues is that even though all the data entries I am parsing should have 'X' amount of fields, there are a good number of fields that are just empty, and sometimes there are tabs that will immediately succeed other tabs.

When I try and access the list of strings from the split file-line, I find myself sometimes getting an IndexOutOfRangeException quite frequently. Would the multiple tabs be causing my list to not always end up with 'X' amount of fields, and therefore throw this exception? If so, is there a way around this?

[EDIT] Heres the code:

string[] parts = line.Split('\t');
String Organization = parts[0];
String SalesRep_FirstName = SalesRep.Split(' ').First();
String SalesRep_LastName = SalesRep.Split(' ').Last();
String Opportunity = parts[1] == "" ? "" : parts[1];
String Type = parts[6] == "" ? comboBox1.SelectedItem.ToString() : parts[6];
String CloseMonth = (parts[5].Split('/'))[0] == "" ? "12" : (parts[开发者_开发问答5].Split('/'))[0];
String CloseDay = (parts[5].Split('/'))[1] == "" ? "21" : (parts[5].Split('/'))[1];
String CloseYear = (parts[5].Split('/'))[2] == "" ? "2012" : (parts[5].Split('/'))[2];
String Stage = (parts[2].Split('-'))[0] == "" ? "1" : (parts[2].Split('-'))[0];
String Probability = parts[4] == "" ? "0" : (Math.Round(decimal.Parse(parts[4]) / 10) * 10).ToString();
String Source = parts[7] == "" ? "" : parts[7];
String Department = Type;
String Product = Opportunity;
String Revenue = parts[3] == "" ? "" : parts[3];

Ideally, each instance of the list parts will have 9 entries, (parts[8] is redundant, so its not referenced here)


You can split a string in two ways:

string input = "x\t\ty\t\t\tz";

char[] separator = new char[] { '\t' };

string[] result1 = input.Split(separator, StringSplitOptions.None);
// result1 == new string[] { "x", "", "y", "", "", "z" }

string[] result2 = input.Split(separator, StringSplitOptions.RemoveEmptyEntries);
// result2 == new string[] { "x", "y", "z" }

If you're using StringSplitOptions.None, then the resulting array should always have the same length -- provided that each input contains the same number of tabs.


That shouldn't be the problem, unless you're using StringSplitOptions.RemoveEmptyEntries.

For example:

string text = "a\t\t\tb";
string[] bits = text.Split('\t');
Console.WriteLine(bits.Length); // 4, of which the middle two are empty

If you can post the code which isn't working (in a short but complete form, ideally) that would help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜