Ejemplo n.º 1
0
    //同个关键词每次替换不同
    public static string ReplaceEveryTimeDifferentWithRegex(this string str, string oldStr, ChangeEveryTimesNewwordDelegate newwordDelegate)
    {
        string newStr;

        while (str.IndexOf(oldStr) > 0)
        {
            Regex regex = new Regex(oldStr);        //要替换字符串
            newStr = newwordDelegate();
            str    = regex.Replace(str, newStr, 1); //最后一个参数是替换的次数
        }
        return(str);
    }
Ejemplo n.º 2
0
    //同个关键词每次替换不同
    public static string ReplaceEveryTimeDifferentWithStringBuilder(this string str, string oldStr, ChangeEveryTimesNewwordDelegate newwordDelegate)
    {
        string newStr;

        //Console.WriteLine("将字符串中的{0}替换成{1}···", oldStr, newStr);
        StringBuilder strBuffer = new StringBuilder();
        int           start     = 0;
        int           tail      = 0;

        //一旦找不到需要替换的字符串(第一次IndexOf返回-1)
        //就说明没有该关键字符串,可以直接返回之前的字符串
        if (str.IndexOf(oldStr) == -1)
        {
            //Console.WriteLine("没有找到需要替换的关键字符串!");
            return(str);
        }

        //每次都不断循环,查找这个x
        //一旦找到了,就把它之前和上一个x之后的字符串拼接起来
        while (true)
        {
            start = str.IndexOf(oldStr, start);
            if (start == -1)
            {
                break;
            }
            strBuffer.Append(str.Substring(tail, start - tail));
            newStr = newwordDelegate();
            strBuffer.Append(newStr);
            start += oldStr.Length;
            tail   = start;
        }

        //查找到最后一个位置之后
        //还要把剩下的字符串拼接进去
        strBuffer.Append(str.Substring(tail));
        return(strBuffer.ToString());
    }