私の個人的な意見では、最もクリーンな解決策は正規表現を使用することです。しかし、それが計算集約的であるかどうかを推測する代わりに、私はむしろそれをベンチマークしたいと思います。これがコードです。
const int Count = 10000000;
const string testString = "<whatever>";
// Solution No. 1: use Regex.Match()
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < Count; i++)
{
var match = Regex.Match(@"\[\s*(\d+)\s*\]$", testString);
if (!match.Success)
continue;
var number = int.Parse(match.Groups[1].Value);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
// Solution No. 2: use IndexOf() and Substring() shenanigans
sw.Start();
for (int i = 0; i < Count; i++)
{
var lb = testString.IndexOf('[');
var rb = testString.LastIndexOf(']');
if (lb < 0 || rb != testString.Length - 1)
continue;
var str = testString.Substring(lb + 1, rb - lb - 1);
int number;
if (!int.TryParse(str, out number))
continue;
// use the number
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
そしてここに結果があります:
Solution | testString | Time (ms) | Comment
----------|--------------|--------------|-----------------------
1 | abc [ ] | 4476 | Invalid input string
2 | abc [ ] | 6594 | Invalid input string
1 | abc[1234] | 4446 | Valid input string
2 | abc[1234] | 6290 | Valid input string
ご覧のとおり、正規表現ソリューションは短くてクリーンであるだけでなく、実際には高速です。また、さまざまな入力文字列で遊んでいる場合、入力文字列が長いほど、最初のソリューションと2番目のソリューションの間のギャップが大きくなることに気付くでしょう。