Vilda
Vilda

Reputation: 1783

Reading a text file with a specific structure

I have a *.txt file, with the structure like this:

"thing 1" "thing 2" "thing 3" "thing 4"
"thing 6" "thing 7" "thing 8" "thing 9"
"thing 10" "thing 11" "thing 12" "thing 13"
"thing 14" "thing 15" "thing 16" "thing 17"
...

how do I extract it from the text file so I could have some string, with value of thing 1, thing 2, etc..

I was only able to read the whole file at once. Or is there another way, how to store some "database" data (maybe excel files?)?

Upvotes: 0

Views: 712

Answers (2)

Aelphaeis
Aelphaeis

Reputation: 2613

Here is a non regex solution. This will give you an array of strings.

using System;
using System.Linq;
using System.Reflection;

public class Program
{
    public static void Main()
    {
        String input = "\"thing 1\" \"thing 2\" \"thing 3\" \"thing 4\"";
        var result = input.Split(new char[]{'\"'}).Where(p=> !String.IsNullOrWhiteSpace(p));
        foreach(string v in result)
            Console.WriteLine(v);
    }
}

Upvotes: 1

Jason
Jason

Reputation: 89082

This is basic C# file IO, really nothing specific to Xamarin or Android.

Note that there are a LOT of ways you could approach this, this is just one way.

// File classes are all in System.IO

// read each line as a string, put it into a list
List<string> data = File.ReadLines(path)

foreach(string s in data) {
  // s is one line of data

  // use Regex to grab each string (System.Text.RegularExpressions)
  foreach(Match match in Regex.Matches(inputString, "\"([^\"]*)\""))
    // match.Value should be the individual value "thing 1", etc
    // you can strip off the "" if you want and then put into your DB
    // or whatever you want to do with it 
  }
}

Upvotes: 1

Related Questions