【问题标题】:Trimming every line in a text file then saving the result to an array修剪文本文件中的每一行,然后将结果保存到数组中
【发布时间】:2014-07-25 18:47:40
【问题描述】:

我需要读取每行都有一个文件名的本地文本文件。每个文件名都需要去掉它的扩展名。当我到达需要将修剪结果保存到另一个数组的部分时,我遇到了一些麻烦。

到目前为止我有:

string path = @"C:\Users\path\file.txt";

      string[] readText = File.ReadAllLines(path);
      foreach (string s in readText)
      {
          string result = Path.GetFileNameWithoutExtension(s);

          //here I can print the result to the screen 
          //but I don't know how to save to another array for further manipulation    

      }

如果您需要任何进一步的说明,我会尽力说得更清楚。 提前致谢。

【问题讨论】:

  • 为什么不直接将值推回向量中?
  • @Papsicle 抱歉,我不知道那是什么意思。为了在这个网站上成长,我必须发一些帖子,这样我才能有足够的代表投票,并对我每个工作日在这里阅读的数百篇帖子表示感谢。还是个菜鸟。
  • 向量是一个动态数组,这意味着你在创建它时不必指定它的长度,当它满时它会自动增加大小。因此,您可以创建一个本地向量,然后只需使用 pushback 方法(实际上只是一个 add 方法)并将您拥有的每个字符串值添加到这个动态数组中。你可以阅读更多here
  • 谢谢@Papsicle。既然你解释了它,我隐约记得那个主题,我现在就去看看。

标签: c# arrays trim


【解决方案1】:

你也可以用 Linq 做到这一点:

var path = @"C:\Users\path\file.txt";
var trimmed =
    File.ReadAllLines(path)
        .Select(Path.GetFileNameWithoutExtension)
        .ToArray();

【讨论】:

    【解决方案2】:

    使用for 循环而不是foreach

    string path = @"C:\Users\path\file.txt";
    string[] readText = File.ReadAllLines(path);
    for( int i = 0; i < readText.Length; i++ )
        readText[i] = Path.GetFileNameWithoutExtension( readText[i] );
    

    【讨论】:

    • 谢谢!这行得通。不,我不需要保存原始数组。
    【解决方案3】:

    分配一个与原数组大小相同的新数组,然后通过索引插入。

      string path = @"C:\Users\path\file.txt";
    
      string[] readText = File.ReadAllLines(path);
      string[] outputArray = new string[readText.Length];
      int index = 0;
      foreach (string s in readText)
      {
          outputArray[index++] = Path.GetFileNameWithoutExtension(s);
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多