How to cut rest of string after substring in c#?
I got a string like this (my readline):
alfa: 10662 beta: -64 gama: 70679 delta: 1001
I need to use some of this numbers as a parameters but these numbers can have varying length. I can imagine that extracting value alfa I can do with:开发者_如何学C
str1 = readline.Substring(6, 5);
But how would I get the value of gamma if the values of beta and alpha can vary?
You can use a regex to match all the name:value
pairs and use capture groups to extract the names and values:
var readline = "alpha: 10662 beta: -64 gamma: 70679 delta: 1001";
var matches = Regex.Matches(readline, @"(?<parameter>\w*):\s*(?<value>-?\d*)");
var dictionary = new Dictionary<string,int>();
foreach (Match m in matches)
{
dictionary.Add(m.Groups["parameter"].Value,int.Parse(m.Groups["value"].Value));
}
Console.WriteLine(dictionary["gamma"]); // output: 70679
I would go about doing it a different way that using substring. First, split on the separators to produce an array of keys/values with the keys in the even positions and the values in the odd positions. Then you can either iterate through the array by 2s choosing the value associated with key desired or, if they are always in the same order, just choose the correct array element to convert.
Apply input validation as needed to make sure you don't have corrupt inputs.
var parameters = line.Split( new [] { ':', ' ' }, StringSplitOptions.RemoveEmptyEntries );
for (var i = 0; i < parameters.Length; i += 2 )
{
var key = parameters[i];
var value = int.Parse( parameters[i+1] );
// do something with the value based on the key
}
It seems like a good fit for a regular expression:
var regex = new Regex(@"(\w+)\:\s(-?\d+)");
var values = from pair in regex.Matches("alfa: 10662 beta: -64 gama: 70679 delta: 1001").OfType<Match>()
select new { Key = pair.Groups[1].Value, pair.Groups[2].Value };
I wouldn't use SubString for this; it will be more verbose and error prone.
At it's simplest, it looks as though all of your data is separated by whitespace. Is this a fair assumption? Is the order of each variable always the same? If so, then you can simply split on whitespace and grab every other number;
If the data is not always of the same form, then I would use a regular expression instead. You can use something of the form:
/alfa: ([+-]\d+)/
Which will capture the number after "alpha:" and the sign. You will need something a bit fancier for floating point values. Honestly, I very rarely use regular expressions, and when I write a non-trivial regex I always use regex buddy, so I don't want to write a comprehensive one here for you as it will take me too long =)
EDIT: See, Mark's Regex is much better than mine.
精彩评论