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#.
The Parse Regex operator (also called the extract operator) enables users comfortable with regular expression syntax to extract more complex data from log lines. Parse regex can be used, for example, to extract nested fields.
Parse(String) method in C# is used to convert the value of the specified string to its equivalent Unicode character.
String parsing in java can be done by using a wrapper class. Using the Split method, a String can be converted to an array by passing the delimiter to the split method. The split method is one of the methods of the wrapper class. String parsing can also be done through StringTokenizer.
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);
}
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(',');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With