繁体   English   中英

如何将文本文件中的行存储到数组中?

[英]How to store a line in a text file into an array?

我有一个问题,我无法解决。 我希望程序(如下所示)将问题的所有行存储在“ temp_q.txt”文件中。 例如,这是一个问题:

C1:谁是约翰·史密斯?

并将问题的单词保存在数组中,然后如果它在“书”中找到了答案,我将其命名为“ core.txt”。它将在文本框中显示答案。2这是代码的一部分:

        private void button2_Click(object sender, EventArgs e)
    {
        if (File.Exists(@"C:\\Users\TEI\Desktop\temp_q.txt"))
        {
            //OK, pff..Now search for the question to answer!
            System.IO.StreamReader keytxt = new System.IO.StreamReader(@"C:\\Users\TEI\Desktop\temp_q.txt");
            String line;
            while ((line = keytxt.ReadLine()) != null)
            {
                if (line.Contains(textBox1.Text))    //If the question has been found...
                {
                    String ctrl1 = String.Empty;
                    ctrl1 = ("Line Found!Beginning Voice Transfer..");
                    richTextBox2.Text = ctrl1;
                    //Here i want to save the question word-by-word in an array.


                    //Begin searching for the right answer in the core



                }
            }

感谢您的一点帮助! 先感谢您!

为了将问题逐字保存到数组中,您可以简单地在代码中声明一个数组,然后将问题放入string变量中,最后使用Split(' ')函数将其拆分为单个单词。 像这样的东西:

string question = "Who is John Smith?";
string[] words = new string[100];
words = question.Split(' ');

您可以在此处根据需要定义数组大小。 这将通过单词之间的whitespaces将整个问题分解。

更新:在Core.txt部分中找到单词:

现在,当您想在该文本文件中搜索某个特定单词时,可以遍历我们刚刚制作的数组,一次搜索一个元素,在您的line对象中搜索匹配项。 像这样的东西:

for (int i = 0; i < words.Length; i++)
{
    if(line.Contains(words[i].ToString())) 
    {
      //put your logic here.
    }
}

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM