Pattern based string parse

2019-01-25 10:37发布

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#.

4条回答
Animai°情兽
2楼-- · 2019-01-25 11:01

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);
}
查看更多
闹够了就滚
3楼-- · 2019-01-25 11:05

Use Split function

var result = "12,Apple,20".Split(',');
查看更多
对你真心纯属浪费
4楼-- · 2019-01-25 11:15

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#

查看更多
甜甜的少女心
5楼-- · 2019-01-25 11:26

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.

查看更多
登录 后发表回答