【问题标题】:Pick a specific line from a text file and spilt the line in an array从文本文件中选择特定行并将该行拆分为数组
【发布时间】:2016-07-14 13:45:58
【问题描述】:

我想做的是从文本文件中选择一行。该行号对应于一个局部变量。因此,如果变量为 1,则选择第一行。该文本文件位于资源中,名为 nl_5.txt。之后,选择的行(一个单词)应该放在一个新的数组中,但每个字母都应该放在一个新的索引处。因此,如果变量为 1,则第一行是 apple。像这样的:

string[] arr1 = new string[] { "a", "p", "p", "l", "e" }; (0=a 1=p 2=p 3=l 4=e)

如果局部变量更改为 2,则应读取第二行,并且应将数组更改为另一行(换句话说,其他字母)。我该怎么做?

我发现了不同的变体,例如读取完整文件或读取已定义的特定行,但我尝试了很多但没有正确的结果。

int lineCount = File.ReadAllLines(@"C:\test.txt").Length;
int count = 0;


private void button1_Click(object sender, EventArgs e)
{
    var reader = File.OpenText(@"C:\test.txt");


    if (lineCount > count)
    {
        textBox1.Text = reader.ReadLine();
        count++;
    }
}

【问题讨论】:

标签: c#


【解决方案1】:

首先,让我们通过Linq获取单词:

 int line = 3; // one based line number

 string word = File
   .ReadLines(@"C:\test.txt") //TODO: put actual file name here
   .Skip(line - 1) // zero based line number
   .FirstOrDefault();

然后将word转换成数组

 string[] arr1 = word
   .Select(c => c.ToString())
   .ToArray(); 

如果您必须读取多个不同line 的文件,您可以缓存该文件:

   // Simplest, not thread safe
   private static string[] file;

   // line is one-based
   private static string[] getMyArray(int line) {
     if (null == file)
       file = File.ReadAllLines(@"C:\test.txt");

     // In case you have data in resource as string
     // read it and (split) from the resource
     // if (null == file)
     //   file = Resources.MyString.Split(
     //     new String[] { Environment.NewLine }, StringSplitOptions.None);

     string word = (line >= 1 && line < file.Length - 1) ? file[line - 1] : null;

     if (null == word)
       return null; // or throw an exception

     return word
       .Select(c => c.ToString())
       .ToArray(); 
   } 

【讨论】:

  • 是否可以从资源中添加文件?
  • @Donovan:如果资源中有text,可以Split转成行:Resources.String.Split(new String[] { Environment.NewLine }, StringSplitOptions.None);
  • 太棒了!我在添加 MessageBox.Show(word); 时进行了检查第一个单词显示为消息框!凉爽的!如何使用第一个 Array 字母更改标签文本?
  • @Donovan:尝试格式化myLabel.Text = String.Format("The first letter is {0}.", arr1[0]);
  • 完美!非常感谢您的支持和时间!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-06
  • 1970-01-01
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-07
相关资源
最近更新 更多