![](/img/trans.png)
[英]string split with delimeters remain in strings result array, how? c#
[英]How to split a string into a array of arrays of strings as fast as possible in C#?
簡短描述:拆分字符串需要很長的時間。
更長的描述:我需要從如下所示的字符串中提取信息:
...
5 1 12 1 1 1 466 1277 458 80 92 Assistance
2 1 13 0 0 0 1055 1277 1717 100 -1
3 1 13 1 0 0 1055 1186 1717 191 -1
4 1 13 1 1 0 1055 1277 1717 100 -1
5 1 13 1 1 1 1055 1279 288 78 90 Vehicle
5 1 13 1 1 2 1489 1279 228 98 67 Lights
5 1 13 1 1 3 1856 1281 286 95 74 System
5 1 13 1 1 4 2284 1281 196 95 70 Apps
5 1 13 1 1 5 2618 1277 154 80 77 Info
...
(旁注:該字符串來自page.GetTsvText(0)方法的返回;page 是TesseractEngine.Process(image)的返回;因此該字符串包含有關檢測到的 OCR 字符串、 conficendes 、邊界框坐標等的信息。 )
為了能夠更輕松地使用這些信息,我編寫了一個方法,將字符串轉換為字符串數組的數組:
private string[][] getDataArray(string source)
{
Stopwatch sw = new Stopwatch();
sw.Start();
Console.WriteLine(source);
string[] rows = source.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
int nrOfRows = rows.Length;
string[][] result = new string[nrOfRows][];
for (int i = 0; i < nrOfRows; i++)
{
result[i] = rows[i].Split(new char[] { ' ', ' ' }, StringSplitOptions.RemoveEmptyEntries);
}
sw.Stop();
Console.WriteLine(" $$$ getDataArray() took: " + sw.ElapsedMilliseconds + " ms");
return result;
}
注意:由於某種原因,字符串包含看起來比通常的空格更長的空格。 我從控制台日志中復制粘貼。 它是單個字符,而不是制表符,但它需要更多空間/比通常的空格字符更寬。
問題:
stopwatch.Restart();
// Get data
string[][] data = getDataArray(page.GetTsvText(0));
stopwatch.Stop();
Console.WriteLine(" $$$ $$$ Got data array in: " + stopwatch.ElapsedMilliseconds + " ms");
大約需要2000 毫秒。
字符串初始化需要這么長時間嗎? 我怎樣才能更快地獲得它,比如低於 50 毫秒?
通過使用 Linq
string[][] result = source.Split('\n')
.Select(line => line.Split(new char[] { ' ', ' ' }, StringSplitOptions.RemoveEmptyEntries));
Linq 具有更好的性能和更快的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.