[英]What is the fastest way to extract a substring from a string, up to a delimiter in C#?
因此,我正在解析一个大文件,并且我需要优化我的字符串提取过程(当前该程序甚至大约需要1-2分钟才能完成文件的解析)。 这是调试和进一步开发软件的杀手。
范例程序
string sample = "First Line\nSecond Line\nThird Line";
string extracted_string = ExtractString(ref sample, "\n");
// extracted_string should hold "First Line"
// sample should hold "Second Line\nThird Line";
ExtractString函数
function string ExtractString(ref string original, string delimiter)
{
int index_of = original.IndexOf(delimiter);
string result = "";
if(index_of >= 0)
{
result = original.Substring(0, index_of);
// Remove string & delimiter from original
original = original.Remove(0, index_of + 1);
}
else
{
result = original;
original = "";
}
return result;
}
我有另一种方法来加快处理速度吗?...到目前为止,每条记录要花费大约50-80ms的处理时间,并且大概有6000-7000条记录。
您应该使用string.Split(char delimeter)方法。 它比对字符串的操作要快得多。 字符串是不可更改的,此特性会导致性能问题。 在每个操作中,都会分配新的内存。 将您的方法更改为:
string sample = "First Line\nSecond Line\nThird Line";
var extracted_strings = sample.Split('\n');
请阅读有关如何在Visual C#中改善字符串连接性能的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.