【问题标题】:Parsing a .txt file as different data types将 .txt 文件解析为不同的数据类型
【发布时间】:2011-10-03 07:10:39
【问题描述】:

所以我有一个文本文件,内容如下

-9
5.23
b
99
Magic
1.333
aa

当我尝试使用以下代码读取它时,GetType() 函数将其输出为字符串:

string stringData;

streamReader = new StreamReader(potato.txt);
while (streamReader.Peek() > 0)
{
    data = streamReader.ReadLine();
    Console.WriteLine("{0,8} {1,15}", stringData, stringData.GetType());
}

然后是输出:

-9      System.String
5.23    System.String
b       System.String
99      System.String
Magic   System.String
1.333   System.String
aa      System.String

我知道我要求 streamReader 类将其全部作为字符串读取。

我的问题是,如何将其读取为不同的数据类型(即字符串、整数、双精度),并将其输出为:

-9      System.int
5.23    System.double
b       System.String
99      System.int
Magic   System.String
1.333   System.double
aa      System.String

【问题讨论】:

    标签: c# parsing types casting


    【解决方案1】:

    您必须将字符串转换为该类型:

    string stringData;
    double d;
    int i;
    
    streamReader = new StreamReader(potato.txt);
    while (streamReader.Peek() > 0)
    {
       data = streamReader.ReadLine();
    
       if (int.TryParse(data, out i) 
       {       
           Console.WriteLine("{0,8} {1,15}", i, i.GetType());
       }
       else if (double.TryParse(data, out d) 
       {       
           Console.WriteLine("{0,8} {1,15}", d, d.GetType());
       }
       else Console.WriteLine("{0,8} {1,15}", data, data.GetType());
    }
    

    【讨论】:

    • 非常感谢。顺便说一句,你为什么用“out”?为什么必须通过引用传递?
    • 我别无选择,tryparse方法有那个参数结构。如果你想让方法返回两个值是一个不错的选择。
    【解决方案2】:

    通常您会知道类型(文件的结构)。

    如果不是,请使用 RegEx 检查可能的 intdouble 值,将其余值返回为 string

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      • 2021-10-17
      • 2013-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多