Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The fastest way to find highest number in document

Tags:

c#

winforms

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);
}
like image 725
Paweł Mikołajczyk Avatar asked Jun 12 '14 07:06

Paweł Mikołajczyk


1 Answers

You can use the following regex to extract number strings between { and } brackets.

(?<={)\d+(?=})

Regular expression visualization

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();
like image 148
Ulugbek Umirov Avatar answered Oct 08 '22 06:10

Ulugbek Umirov