简体   繁体   中英

The fastest way to find highest number in document

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM