我有这样的文件:
[...]
UTS+48:::{7}:{8}+{9}'
UTB+454343::34343+{10}-{12}'
[...]
在我的表单中选择文件后,我将整个文件读入一个字符串。现在,我需要找到这些括号 {} 之间的最大数字。最好的解决方案是什么?我已经解决了这个问题,但我认为我的解决方案并不是最好的。我正在考虑使用一些正则表达式,但我不知道如何正确使用它。
这是我的解决方案:
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);
}
最佳答案
您可以使用以下正则表达式提取 {
和 }
括号之间的数字字符串。
(?<={)\d+(?=})
然后将提取的字符串转换为数字并找到最大值。
示例代码:
string s = "{5} + {666}";
long max = Regex.Matches(s, @"(?<={)\d+(?=})")
.Cast<Match>()
.Select(m => long.Parse(m.Value))
.Max();
关于c# - 在文档中查找最高数字的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24179029/