开发者

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

开发者 https://www.devze.com 2023-03-04 02:31 出处:网络
I have this str开发者_如何学Going 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 v

I have this str开发者_如何学Going 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)


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.


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]);
        }
    }


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.


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]);
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消