[英]Parsing a .txt file as different data types
So I have a text file that reads as the following 所以我有一个文本文件,内容如下
-9
5.23
b
99
Magic
1.333
aa
When I try to read it in using the following code, the GetType() function outputs it as strings: 当我尝试使用以下代码读取它时,GetType()函数将其输出为字符串:
string stringData;
streamReader = new StreamReader(potato.txt);
while (streamReader.Peek() > 0)
{
data = streamReader.ReadLine();
Console.WriteLine("{0,8} {1,15}", stringData, stringData.GetType());
}
Here then is the output: 然后是输出:
-9 System.String
5.23 System.String
b System.String
99 System.String
Magic System.String
1.333 System.String
aa System.String
I understand that I asked the streamReader class to read it all in as strings. 我了解我要求streamReader类以字符串形式全部读取它。
My question is, how does one read it as the different different data types (ie string, int, double), and have it output as: 我的问题是,如何将其读取为不同的不同数据类型(例如,字符串,整数,双精度),并将其输出为:
-9 System.int
5.23 System.double
b System.String
99 System.int
Magic System.String
1.333 System.double
aa System.String
You have to convert string to that types: 您必须将字符串转换为该类型:
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());
}
Normally you would know the types (the structure of the file). 通常,您会知道类型(文件的结构)。
If not, use RegEx to check for possible int
and double
values, return the rest as string
. 如果不是,请使用RegEx检查可能的int
和double
值,然后将其余值作为string
返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.