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

本文关键字:最佳 方式 文本 替换 字符串 | 更新日期: 2023-09-27 18:03:41

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

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中的"words",看看parameters中是否有匹配,取"replacement"值并建立一个新字符串,但我怀疑额外的查找将比多次重新创建字符串值花费更多。

在任何情况下,应该考虑两个重要的性能改进原则:

  • 首先从最慢的部分开始——你可能会看到一些改进,但如果它不能显著提高整体性能,那么它就无关紧要了
  • 知道一个特定的改变是否会提高你的表现(以及提高多少)的唯一方法是两种方法都尝试并测量它。

StringBuilder将具有更少的内存开销和更好的性能,特别是在大字符串上。String.Replace() vs. 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个项目,这可能不会更好。这个问题的答案很好地分析了您期望看到的性能改进。