zoukankan      html  css  js  c++  java
  • asp.net仿搜索引擎关键字高亮.搜索高亮

    以前做关键字高亮都是直接使用replace方法直接替换

    string input="AAbCC";

    string keyword="b";

    input=input.ToUpp();

    keyword=keyword.ToUpp();

    s=s.Replace(keyword,"<font>"+keyword+"</font>");

    如果这样

    输出: "AABCC"

    可以发现B已经被转换成大写形式了.

    在网上找了很多没有找到解决问题根本的方法,找到一个使用正则表达式做的,

    个人觉得在for循环里面使用正则表达式相当耗费性能.

    于是乎自己写了一个 , 代码如下

            /// <summary>
            /// 高亮关键字
            /// </summary>
            /// <param name="input">输入的字符串</param>
            /// <param name="keyword">需要高亮的关键字</param>
            /// <param name="color">高亮的颜色  默认值:#ff0000</param>
            /// <returns></returns>
            public static string HighLightKeyWord(string input, string keyword, string color)
            {
                color = color == "" ? "#ff0000" : color;
                string input2 = input.ToUpper();
                string keyword2 = keyword.ToUpper();
                int l = 0;
                while (true)
                {
                    int input2IndexOf = input2.IndexOf(keyword2);
                    if (input2IndexOf <= -1)
                        break;
                    input = input.Insert(input2IndexOf + l, "<font color='" + color + "'>").Insert(input2IndexOf + keyword2.Length + 15 + color.Length + l, "</font>");
                    input2 = input2.Remove(input2IndexOf, keyword2.Length);
                    l = keyword2.Length + l + 22 + color.Length;
                }
                return input;
            }

     虽然很简单的实现原理,但是网上并无此类解决方式,特此贴出共享.

  • 相关阅读:
    63. Unique Paths II(中等, 能独立做出来的DP类第二个题^^)
    3.2 2-dim Vector Initialization
    62. Unique Paths(中等,我自己解出的第一道 DP 题^^)
    漫画:什么是动态规划?
    120. Triangle(中等)
    128. Longest Consecutive Sequence
    80. Remove Duplicates from Sorted Array II
    81. Search in Rotated Sorted Array II (中等)
    59. Spiral Matrix II(中等,同54题)
    spring cloud
  • 原文地址:https://www.cnblogs.com/337212522/p/2534430.html
Copyright © 2011-2022 走看看