[英]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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.