C# 如何在从文本文件读取字符串后对其进行解析

C# 如何在从文本文件读取字符串后对其进行解析,c#,regex,string,parsing,C#,Regex,String,Parsing,假设我有一个文本文件,其中包含“1本书的价格$12.00”。我想读一本书 并设置我的局部变量,如整数数量、字符串产品类型、双倍价格等。 读取文件后,我的变量值应为 quantity = 1; product_type = Book; price = 12.00; 你能告诉我怎么做吗?有什么原因迫使你使用文本文件来存储数据吗?XML将是存储和解析此类数据的更好、更简单的方法 string str = "1 Book price $12.00"; string[] strArray = s

假设我有一个文本文件,其中包含“1本书的价格$12.00”。我想读一本书 并设置我的局部变量,如整数数量、字符串产品类型、双倍价格等。 读取文件后,我的变量值应为

quantity  = 1;
product_type  = Book;
price = 12.00;

你能告诉我怎么做吗?

有什么原因迫使你使用文本文件来存储数据吗?XML将是存储和解析此类数据的更好、更简单的方法

 string str = "1 Book price $12.00";
 string[] strArray = str.Split(' ');
 int quantity = Convert.ToInt32(strArray[0]);
 string product_type = strArray[1];
 decimal price = Convert.ToDecimal(strArray[3].Replace("$", ""));
<Books>
    <Book>
        <Quantity>1</Quantity>
        <Price>12</Price>
    </Book>
</Books>

1.
12

有很多选项可以解析这个。您可以使用XMLDocument、XMLReader、XElement等加载此文件并解析单个元素。如果在文本文件中添加更复杂的数据,基于索引的字符串操作往往会变得丑陋且容易出错。

您可以使用XML,也可以查找JSON

语法非常简单,甚至比XML更轻量级

您可以将其直接读入类对象

JSON的外观示例如下:-

[
    {
        "Qty": 1,
        "ProductType": "Book",
        "Price": 12.01
    },
    {
        "Qty": 1,
        "ProductType": "Pen",
        "Price": 12.01
    }
]
下面是一段代码片段。您需要添加对Newtonsoft JSON的引用

using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

namespace JSONExample
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            LoadJson();
        }

        public static void LoadJson()
        {
            using (StreamReader r = new StreamReader(@"C:\Users\Derek\Desktop\JSON.txt"))
            {
                string json = r.ReadToEnd();
                List<Product> dataFile = JsonConvert.DeserializeObject<List<Product>>(json);

                foreach (var product in dataFile.ToArray())
                {
                    Console.WriteLine("Type: {0} - Price: {1} - Quantity: {2}", product.ProductType, product.Price,
                        product.Qty);
                }
            }

            Console.ReadKey();
        }
    }



    public class Product
    {
        public int Qty { get; set; }
        public string ProductType { get; set; }
        public float Price { get; set; }
    }

}
使用系统;
使用System.Collections.Generic;
使用System.IO;
使用Newtonsoft.Json;
名称空间JSONExample
{
内部课程计划
{
私有静态void Main(字符串[]args)
{
LoadJson();
}
公共静态void LoadJson()
{
使用(StreamReader r=newstreamreader(@“C:\Users\Derek\Desktop\JSON.txt”))
{
字符串json=r.ReadToEnd();
List dataFile=JsonConvert.DeserializeObject(json);
foreach(dataFile.ToArray()中的var product)
{
Console.WriteLine(“类型:{0}-价格:{1}-数量:{2}”),product.ProductType,product.Price,
产品数量);
}
}
Console.ReadKey();
}
}
公共类产品
{
公共整数数量{get;set;}
公共字符串ProductType{get;set;}
公开浮动价格{get;set;}
}
}

您可以使用Split()函数获取字符串[],然后将值解析为int(第一个索引-数量)和double(最后一个索引-价格)。但更好的解决方案是对这种结构化数据使用Xml文件。另外,您也可以使用正则表达式来解析文本文件,但XML文件仍然是一个更好的解决方案。如果您要创建此文件,请将其存储为结构化XML文件,以便于继续维护代码。。如果您是从无法控制格式的外部系统获取此文件,请使用split(),并且您的代码具有足够的防御能力来处理null、空字符串等。