简体   繁体   中英

Pattern based string parse

When I need to stringify some values by joining them with commas, I do, for example:

string.Format("{0},{1},{3}", item.Id, item.Name, item.Count);

And have, for example, "12,Apple,20" .
Then I want to do opposite operation, get values from given string. Something like:

parseFromString(str, out item.Id, out item.Name, out item.Count);

I know, it is possible in C. But I don't know such function in C#.

Yes, this is easy enough. You just use the String.Split method to split the string on every comma.

For example:

string myString = "12,Apple,20";
string[] subStrings = myString.Split(',');

foreach (string str in subStrings)
{
    Console.WriteLine(str);
}

Possible implementations would use String.Split or Regex.Match

example.

public void parseFromString(string input, out int id, out string name, out int count)
{
    var split = input.Split(',');
    if(split.length == 3) // perhaps more validation here
    {
        id = int.Parse(split[0]);
        name = split[1];
        count = int.Parse(split[2]);     
    }
}

or

public void parseFromString(string input, out int id, out string name, out int count)
{
    var r = new Regex(@"(\d+),(\w+),(\d+)", RegexOptions.IgnoreCase);
    var match = r.Match(input);
    if(match.Success)
    {
        id = int.Parse(match.Groups[1].Value);
        name = match.Groups[2].Value;
        count = int.Parse(match.Groups[3].Value);     
    }
}

Edit: Finally, SO has a bunch of thread on scanf implementation in C#
Looking for C# equivalent of scanf
how do I do sscanf in c#

If you can assume the strings format, especially that item.Name does not contain a ,

void parseFromString(string str, out int id, out string name, out int count)
{
    string[] parts = str.split(',');
    id = int.Parse(parts[0]);
    name = parts[1];
    count = int.Parse(parts[2]);
}

This will simply do what you want but I would suggest you add some error checking. Better still consider serializing/deserializing to XML or JSON.

Use Split function

var result = "12,Apple,20".Split(',');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM