繁体   English   中英

替换字符串中文本的最佳方法

[英]Best way to replace text in string

寻找更好的算法/技术来替换字符串变量中的字符串。 我必须遍历未知数目的数据库记录,并且对于每个记录,我需要替换字符串变量中的一些文本。 现在看起来像这样,但是必须有更好的方法:

using (eds ctx = new eds())
{
    string targetText = "This is a sample string with words that will get replaced based on data pulled from the database";

    List<parameter> lstParameters = ctx.ciParameters.ToList();
    foreach (parameter in lstParameters)
    {
        string searchKey = parameter.searchKey;
        string newValue = parameter.value;
        targetText = targetText.Replace(searchKey, newValue);
    }
}

从我的理解来看,这不好,因为我在循环中一遍又一遍地写了targetText变量。 但是,我不确定查找和替换的结构...

感谢任何反馈。

一定有更好的方法

字符串是不可变的-您不能“更改”它们-您所能做的就是创建一个字符串并替换变量值(这并不像您想的那样糟糕)。 您可以尝试使用StringBuilder作为其他建议,但是不能保证100%改善性能。

可以更改算法以遍历targetText的“单词”,查看parameters是否匹配,获取“ replacement”值并构建新的字符串,但是我怀疑额外的查找会比重新创建字符串值花费更多多次。

无论如何,应该考虑两个重要的绩效改进原则:

  • 首先从应用程序最慢的部分开始-您可能会看到一些改进,但是如果它不能显着提高整体性能,那么没关系
  • 知道某个特定更改是否会提高您的性能(以及提高多少)的唯一方法是同时尝试并评估它。

StringBuilder将具有较少的内存开销和更好的性能,尤其是在大型字符串上。 String.Replace()与StringBuilder.Replace()

using (eds ctx = new eds())
{
    string targetText = "This is a sample string with words that will get replaced based on data pulled from the database";

    var builder = new StringBuilder(targetText);

    List<parameter> lstParameters = ctx.ciParameters.ToList();
    foreach (parameter in lstParameters)
    {
        string searchKey = parameter.searchKey;
        string newValue = parameter.value;
        targetText = builder.Replace(searchKey, newValue);
    }
}

其实, 一个更好的答案,假设你正在做大量的更新换代。 您可以使用StringBuilder 如您所知,字符串是不可变的。 因此,正如您所说,您正在循环中一遍又一遍地创建字符串。

如果将字符串转换为StringBuilder

StringBuilder s = new StringBuilder(s, s.Length*2); // Adjust the capacity based on how much bigger you think the string will get due to replacements. The more accurate your estimate, the better this will perform.

  foreach (parameter in lstParameters)
    {
        s.Replace(parameter.searchKey, parameter.value);
    }
  string targetString = s.ToString();

现在需要注意的是,如果您的列表中只有2-3个项目,这可能再好不过了。 在回答这个问题提供的,你可以期望看到的性能提升一个很好的分析。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM