I have got file which looks like this:
[...]
UTS+48:::{7}:{8}+{9}'
UTB+454343::34343+{10}-{12}'
[...]
After choosing file in my Form, I read whole file into a single string. Now, I need to find the highest number between these brackets {}. What will be the best solution for that? I have already solved that, but my solution isn't the best in my opinion. I was thinking about using some Regex but I honsetly don't know how to use it properly.
Here is my solution:
private int GetNumberOfParameters(string text)
{
string temp = File.ReadAllText(text);
string number = String.Empty, highestNumber = String.Empty;
bool firstNumber = true;
for (int i = 0; i < temp.Length; i++)
{
if (temp[i].Equals('{'))
{
int j = i;
j++;
while (!temp[j].Equals('}'))
{
number += temp[j];
j++;
}
if (firstNumber)
{
highestNumber = number;
number = String.Empty;
firstNumber = false;
}
else if (Int16.Parse(number) > Int16.Parse(highestNumber))
{
highestNumber = number;
number = String.Empty;
}
else
{
number = String.Empty;
}
}
}
if (highestNumber.Equals(String.Empty))
return 0;
else
return Int16.Parse(highestNumber);
}
You can use the following regex to extract number strings between {
and }
brackets.
(?<={)\d+(?=})
Then you convert extracted strings into numbers and find the maximum one.
Sample code:
string s = "{5} + {666}";
long max = Regex.Matches(s, @"(?<={)\d+(?=})")
.Cast<Match>()
.Select(m => long.Parse(m.Value))
.Max();
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