Pattern based string parse
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#
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);
}
Use Split function
var result = "12,Apple,20".Split(',');
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.