user2472212
user2472212

Reputation: 1

How to Parse the string after reading it from a text file

Let say i have a text file which contain " 1 Book price $12.00" . I want to read this sting from a and set my local variable like int quantity , string product_type , Double price etc. After reading the file, my variable values should be

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

Can you suggest me how to do that?

Upvotes: 0

Views: 126

Answers (3)

Derek
Derek

Reputation: 8640

You could use XML, or you could look up JSON Here

The syntax is really easy, and its even more lightweight than XML.

You can read this directly into Class Objects.

An Example of what the JSON would look like :-

[
    {
        "Qty": 1,
        "ProductType": "Book",
        "Price": 12.01
    },
    {
        "Qty": 1,
        "ProductType": "Pen",
        "Price": 12.01
    }
]

Here's a Code Snippet. You will need to add a reference to 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; }
    }

}

Upvotes: 1

BeingDev
BeingDev

Reputation: 426

 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("$", ""));

Upvotes: -1

Piyush Parashar
Piyush Parashar

Reputation: 874

Is there any reason why you would be compelled to use a text file to store data? XML would be much better and easier way to store and parse this kind of data.

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

There are plenty of options to parse this. You can use XMLDocument, XMLReader, XElement etc you load this file and parse individual elements. Index based string manipulates tend to get ugly and error prone if you add more complex data in your text file.

Upvotes: 1

Related Questions