下面輸入文件從文本文件中提取一些特定的結果在C#
輸入文件
a 00002098 0 0.75 unable#1 (usually followed by `to') not having the necessary means or skill or know-how; "unable to get to town without a car"; "unable to obtain funds"
a 00002312 0.23 0.43 dorsal#2 abaxial#1 facing away from the axis of an organ or organism; "the abaxial surface of a leaf is the underside or side facing away from the stem"
a 00023655 0 0.5 outside#10 away#3 able#2 (of a baseball pitch) on the far side of home plate from the batter; "the pitch was away (or wide)"; "an outside pitch"
而且我想這個文件
輸出
a,00002098,0,0.75,unable#1
a,00002312,0.23,0.43,dorsal#2
a,00002312,0.23,0.43,abaxial#1
a,00023655,0, 0.5,outside#10
a,00023655,0, 0.5,away#3
a,00023655,0, 0.5,able#2
以下結果
我寫下面的代碼提取這樣的上述結果
TextWriter tw = new StreamWriter("D:\\output.txt");
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != null)
{
StreamReader reader = new StreamReader(@"C:\Users\Zia\Desktop\input.txt");
string line;
String lines = "";
while ((line = reader.ReadLine()) != null)
{
String[] str = line.Split('\t');
String[] words = str[3].Split(' ');
for (int k = 0; k < words.Length; k++)
{
for (int i = 0; i < str.Length; i++)
{
if (i + 1 != str.Length)
{
lines = lines + str[i] + ",";
}
else
{
lines = lines + words[k] + "\r\n";
}
}
}
}
tw.Write(lines);
tw.Close();
reader.Close();
}
}
當我改變索引,該代碼提供了以下錯誤,而不是給出的慾望的結果。
錯誤
索引超出了數組的範圍。
在此先感謝。
當你通過代碼進行調試,當異常發生時,你檢查了你正在使用的索引和數組的大小嗎? – Oded
@Oded:我檢查所有索引表格2至5,但給出相同的結果: –
'if(i + 1!= str.Length)'是可疑的。如果'i == str.Length'會發生什麼? – Oded