[英]How to split a string into a array of arrays of strings as fast as possible in C#?
Short description: Splitting a string takes way to long.简短描述:拆分字符串需要很长的时间。
Longer description: I need to extract information from a string looking like this:更长的描述:我需要从如下所示的字符串中提取信息:
...
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
...
(Side Note: the string comes as a return from the page.GetTsvText(0) method; page is a return of TesseractEngine.Process(image) ; so the string contains information about detected OCR strings , conficendes , bounding boxes coords , etc.) (旁注:该字符串来自page.GetTsvText(0)方法的返回;page 是TesseractEngine.Process(image)的返回;因此该字符串包含有关检测到的 OCR 字符串、 conficendes 、边界框坐标等的信息。 )
In order to be able to make easier use of the information, I wrote a method that turns the string into a array of arrays of strings :为了能够更轻松地使用这些信息,我编写了一个方法,将字符串转换为字符串数组的数组:
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;
}
Note: For some reason the string contains spaces that look longer than the usual spaces.注意:由于某种原因,字符串包含看起来比通常的空格更长的空格。 I took it with copy-paste from the console log.
我从控制台日志中复制粘贴。 It is a single character, not a tab, but it takes more space/ is wider than the usual space char.
它是单个字符,而不是制表符,但它需要更多空间/比通常的空格字符更宽。
Problem:问题:
stopwatch.Restart();
// Get data
string[][] data = getDataArray(page.GetTsvText(0));
stopwatch.Stop();
Console.WriteLine(" $$$ $$$ Got data array in: " + stopwatch.ElapsedMilliseconds + " ms");
it takes about 2000 ms .大约需要2000 毫秒。
Does the string initialisation take so long ?字符串初始化需要这么长时间吗? How can I get it faster, like under 50 ms ?
我怎样才能更快地获得它,比如低于 50 毫秒?
By using Linq通过使用 Linq
string[][] result = source.Split('\n')
.Select(line => line.Split(new char[] { ' ', ' ' }, StringSplitOptions.RemoveEmptyEntries));
Linq has better performance and a faster result. Linq 具有更好的性能和更快的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.