【问题标题】:Data structure for a file文件的数据结构
【发布时间】:2018-12-09 01:59:52
【问题描述】:

我有一个文档(文件),我想逐行读取它并拆分成一个字符串(单词)。现在的问题是我想为每个单词分配一个从 0 到依此类推的索引或数字一行,至于新行,我想再次为其分配一个索引或数字,从 0 到依此类推。

***文件示例:

我有一只狗

WDC 是美国的首都

珠穆朗玛峰是最高的山峰

***所需输出:

0:i 1:有 2:a 3:狗

0:WDC 1:is 2:the 3:capital 4:of 5:USA

0:山 1:珠穆朗玛峰 2:是 3:最高点 4:最高点 5:山峰

while ((line = file.ReadLine()) != null)
        {
            string[] words = line.Split(' ');
}

现在我该怎么办?

【问题讨论】:

  • 您可以将words 保存在ArrayList<String []> 中。
  • ArrayList list= new ArrayList();为什么我不能将字符串添加到列表中,不显示 .add 方法
  • 您从未标记过一种语言。看起来像 Java 代码,但再看一遍,它看起来像 C#?
  • 不好意思说是c#
  • 在 C# 中你会使用List<string []>

标签: arrays list data-structures file-handling


【解决方案1】:

您可以将单词保存在 List<string []> 中。

List<string []> data = new List<string []>();
// Read file
while ((line = file.ReadLine()) != null) {
    data.Add(line.Split(' '));
}
// Print results
for (int line = 0; line < data.Count; line++) {
    Console.Write("{0}: ", line);
    for (int word = 0; word < data[line].Length; word++) {
        Console.Write("{0}:{1} ", word, data[line][word]);
    }
    Console.WriteLine();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 2020-09-16
    • 2015-11-29
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多