erfref
erfref

Reputation: 3

parsing a long string in c# and giving those values to parameters

I have this string in C# -

".... School||Abc\r\n...State||CA\r\n..."

The school and state are somewhere in the string. I need to parse the string in such a way that i get the values of School and State for my parameters

string school = abc (from String after parsing)
string state = CA (from string after parsing)

Upvotes: 0

Views: 548

Answers (4)

FIre Panda
FIre Panda

Reputation: 6637

Assuming that your string just contains values separated by "||", "\r" or "\n".

string str = "School||Abc\r\n||State||CA\r\n||AA||AA"; str = str.Trim(); str = str.Replace("\r",string.Empty); str = str.Replace("\n", string.Empty);

        string[] keyValue = str.Split(new string[] { "||" }, StringSplitOptions.None);
        Dictionary<string, string> KeyValDic = new Dictionary<string, string>();

        for (int i = 0; i < keyValue.Length; i++,i++)
        {
            KeyValDic.Add(keyValue[i], keyValue[i + 1]);
        }

Upvotes: 0

YetAnotherUser
YetAnotherUser

Reputation: 9356

Try split-ing string on new line chars and then it looks like a dictionary, with key values separated by ||. Another split on "||" should give you what you want.

Back of the envelope code

  private static void ParseMyString(string longString) {
        IEnumerable<string> shortStrings = longString.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);


        foreach(var ss in shortStrings) {
            var kvp = ss.Split("||".ToCharArray());
            Console.WriteLine("{0} - {1}", kvp[0], kvp[1]);
        }
    }

Upvotes: 1

Chad
Chad

Reputation: 19619

Try this:

string longStr = "School||Abc\r\nState||CA\r\n";
string[] keyValPairs = s.Split("\r\n".ToCharArray());
Dictionary<string, string> info = new Dictionary<string, string>();

foreach(string pair in keyValPairs)
{
   string[] split = pair.Split("||");
    //split[0] is the key, split[1] is the value
   info.Add(split[0], split[1]);
}

Now you can access what you need like so:

string school = info["School"];
string state = info["State"];

Where the longStr variable is just your long string that you start out with, not neccessarily what I set it to.

Upvotes: 3

Oded
Oded

Reputation: 499172

You can use the TextFieldParser class to parse this file, in particular if it is fixed width fields or has known delimiters.

It:

Provides methods and properties for parsing structured text files.

Though it lives in the Microsoft.VisualBasic.Text namespace, it is a .NET assembly and can be used in all .NET projects.

Upvotes: 0

Related Questions