在搜索项子字符串的索引处插入

本文关键字:索引 插入 字符串 搜索 | 更新日期: 2023-09-27 17:54:15

我试图在显示结果中突出显示搜索词。一般情况下,它的工作OK基于代码在这里找到SO。我的问题是,它用搜索词替换了子字符串,即在这个例子中,它将用"LOVE"替换"LOVE"(不可接受)。所以我想我可能需要找到子字符串开始的索引,对开始的标记,并在子字符串的末尾执行类似操作。由于yafs可能相当长,我也认为我需要将stringbuilder集成到这个。这是可行的,还是有更好的方法?一如既往,提前感谢您的建议。

string yafs = "Looking for LOVE in all the wrong places...";
string searchTerm = "love";
yafs = yafs.ReplaceInsensitive(searchTerm, "<span style='background-color: #FFFF00'>" 
+  searchTerm + "</span>");

在搜索项子字符串的索引处插入

这个怎么样:

public static string ReplaceInsensitive(string yafs, string searchTerm) {
    return Regex.Replace(yafs, "(" + searchTerm + ")", "<span style='background-color: #FFFF00'>$1</span>", RegexOptions.IgnoreCase);
}
更新:

public static string ReplaceInsensitive(string yafs, string searchTerm) {
    return Regex.Replace(yafs,
        "(" + Regex.Escape(searchTerm) + ")", 
        "<span style='background-color: #FFFF00'>$1</span>",
        RegexOptions.IgnoreCase);
}

检查此代码

    private static string ReplaceInsensitive(string text, string oldtext,string newtext)
    {
        int indexof = text.IndexOf(oldtext,0,StringComparison.InvariantCultureIgnoreCase);
        while (indexof != -1)
        {
            text = text.Remove(indexof, oldtext.Length);
            text = text.Insert(indexof, newtext);

            indexof = text.IndexOf(oldtext, indexof + newtext.Length ,StringComparison.InvariantCultureIgnoreCase);
        }
        return text;
    }

你需要什么:

static void Main(string[] args)
{
    string yafs = "Looking for LOVE in all the wrong love places...";
    string searchTerm = "LOVE";
    Console.Write(ReplaceInsensitive(yafs, searchTerm));
    Console.Read();
}
private static string ReplaceInsensitive(string yafs, string searchTerm)
{
    StringBuilder sb = new StringBuilder();
    foreach (string word in yafs.Split(' '))
   {
        string tempStr = word;
        if (word.ToUpper() == searchTerm.ToUpper())
        {
            tempStr = word.Insert(0, "<span style='background-color: #FFFF00'>");
            int len = tempStr.Length;
            tempStr = tempStr.Insert(len, "</span>");
        }
        sb.AppendFormat("{0} ", tempStr);
    }
    return sb.ToString();
}

给:

查找LOVE在所有错误love地方…