[英]The fastest way to find highest number in document
我有一個看起來像這樣的文件:
[...]
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.