【问题标题】:Read text file and save numbers to intergers读取文本文件并将数字保存为整数
【发布时间】:2017-02-23 14:55:29
【问题描述】:

我有一个文本文件,我需要按类型保存特定项目。所以我必须将数字保存为整数,将特定单词保存为字符串。

这是我目前所拥有的:

string line;
int sizeOne;
int sizeTwo;
StreamReader file = new StreamReader(@"C:\Users\Asus\Documents\text.txt");
while ((line = file.ReadLine()) != null)
{
    Console.WriteLine(line);
}
file.Close();

Console.ReadKey();

.txt 文件是:

[header]
name = "Simple Maze"
size = 9,10
[/header]

[level]
xxxxxxxxx
x..xsx..x
x.xx.xx.x
x.......x
x..x.x..x
x..xxx..x
x.......x
x.xx.xx.x
x.x.t.x.x
xxxxxxxxx
[/level]

【问题讨论】:

  • 您遇到了什么问题?
  • 如果你混合了数字和字符串,你可以使用 int.TryParse(string, out number),如果字符串可解析为 int,则此方法返回 true 或 false。但是您的文件似乎只有字符串,除了第三行。

标签: c# streamreader readline


【解决方案1】:

由于您正在遍历这些行,因此您可以在每一行检查它是否Contains 某个字符串。

如果您找到了这一行,那么您可以使用 String.Split 方法扭曲您需要的值

如果您已经从文件中提取了值,那么您应该Convert them to integer

这基本上是文字中的算法。现在由你来把它塑造成代码。

您可以在 StackOverflow 上找到每个步骤的示例。玩得开心

【讨论】:

    猜你喜欢
    • 2017-10-17
    • 1970-01-01
    • 2013-08-22
    • 2017-02-18
    • 2014-09-03
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    相关资源
    最近更新 更多