如何从文本文件中读取字符串后分析字符串

本文关键字:字符串 读取 文本 文件 | 更新日期: 2023-09-27 18:31:29

假设我有一个文本文件,其中包含" 1本书价格$ 12.00" 。我想从并设置我的局部变量,如整数、字符串product_type、双倍价格等。读取文件后,我的变量值应该是

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

你能建议我怎么做吗?

如何从文本文件中读取字符串后分析字符串

有什么

理由让你被迫使用文本文件来存储数据吗?XML 将是存储和分析此类数据的更好、更简单的方法。

<Books>
    <Book>
        <Quantity>1</Quantity>
        <Price>12</Price>
    </Book>
</Books>

有很多选项可以解析它。您可以使用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; }
    }
}
 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("$", ""));