使用streamreader C#将单个单词读入数组

时间:2014-05-02 18:19:47

标签: c# arrays csv streamreader

我正在尝试将一个单词列表(下面)放入一个数组中。我希望每个单词都在其自己的索引中。

这是我到目前为止的代码。

string badWordsFilePath = openFileDialog2.FileName.ToString();
StreamReader sr = new StreamReader(badWordsFilePath);
string line = sr.ReadToEnd();
string[] badWordsLine = line.Split(' ');
int BadWordArrayCount = 0;
foreach (string word in badWordsLine)
{
    badWords[BadWordArrayCount] = word;
    BadWordArrayCount = BadWordArrayCount + 1;
}
int test = badWords.Length;
MessageBox.Show("Words have been imported!");
BadWordsImported = true;

以下是我要导入的单词列表。

label
invoice
post
document
postal
calculations
copy
fedex
statement
financial
dhl
usps
8
notification
n
irs
ups
no
delivery
ticket

如果有人能给我一个如何让它发挥作用的例子,那将是一个巨大的帮助。

5 个答案:

答案 0 :(得分:4)

简化代码:

string badWordsFilePath = openFileDialog2.FileName.ToString();
string[] badWords = File.ReadAllLines(badWordsFilePath);
int test = badWords.Length;
MessageBox.Show("Words have been imported!");
BadWordsImported = true;

答案 1 :(得分:3)

如果每个单词都以新行开头,那么您不需要创建for循环。 Split方法将为您转换为数组。

string badWordsFilePath = openFileDialog2.FileName.ToString();
StreamReader sr = new StreamReader(badWordsFilePath);
string line = sr.ReadToEnd();

string[] badWords = line.Split('\n');

答案 2 :(得分:0)

你在空间上分裂,但每个单词之间有一个换行符。在换行符上拆分:

string[] badWordsLine = line.Split(new string[]{ Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

然后你必须创建数组以将单词放在:

badWords = new string[badWordsLine.Length];

然而,循环一个字符串数组只是为了将字符串复制到字符串数组似乎毫无意义。只是将字符串数组赋值给变量。此外,您忘记关闭流阅读器,最好使用using块进行处理:

string badWordsFilePath = openFileDialog2.FileName.ToString();
string line;
using (StreamReader sr = new StreamReader(badWordsFilePath)) {}
  line = sr.ReadToEnd();
}
badWords = line.Split(new string[]{ Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
int test = badWords.Length;
MessageBox.Show("Words have been imported!");
BadWordsImported = true;

答案 3 :(得分:0)

也许尝试这个修改?它允许在各种白色空间上分裂。

     string badWordsFilePath = openFileDialog2.FileName.ToString();
            StreamReader sr = new StreamReader(badWordsFilePath);
            string line = sr.ReadToEnd();
            string[] badWordsLine = line.Split(new string[] {" ", "\t", "\r\n"}, StringSplitOptions.RemoveEmptyEntries);
            int BadWordArrayCount = 0;
            foreach (string word in badWordsLine)
            {
                badWords[BadWordArrayCount] = word;
                BadWordArrayCount = BadWordArrayCount + 1;
            }
            int test = badWords.Length;
            MessageBox.Show("Words have been imported!");
            BadWordsImported = true;

答案 4 :(得分:0)

您必须使用StreamReader吗?如果你没有,那么这段代码就更清楚了(在我看来)。

string text = File.ReadAllText(badWordsFilePath);
string[] words = Regex.Split(text, @"\s+");

如果你100%确定每个单词都在它自己的行上并且没有空行,那么这可能是过度的;和@Ulugbek Umirov的File.ReadAllLines建议更简单。