Reputation: 830
Having a string such as:
string foo = "10::12"
How can I split the string but still mantaining the positions of the results?
To clarify, foo
is dynamic, in a way that in a given time the string may just be ::12
. Using a simple split, I don't know if the resulting 12
was on the left of the separator or on the right.
Thanks!
Upvotes: 0
Views: 125
Reputation: 11808
If you use a regex to find all the numbers, you can use the Index property of the Match class to find both the number and the index of that number.
Regex regex = new Regex(@"\d+");
foreach (Match match in regex.Matches("10::12"))
{
Console.WriteLine($"{match.Index}, {match.Value}");
}
Ouput:
0, 10
4, 12
Upvotes: 1
Reputation: 3239
Try something like this:
public static void Main()
{
ParseAndPrint("::12");
ParseAndPrint("10::12");
}
private static void ParseAndPrint(string input)
{
string[] parts = input.Split(new[] {"::"}, StringSplitOptions.None);
var left = parts[0];
var right = parts[1];
Console.WriteLine("L:" + left + " R:" + right);
}
https://dotnetfiddle.net/rHw07f
Upvotes: 1