代码改变世界

内容替换(限制替换次数)

2010-10-28 16:03  hailibu  阅读(336)  评论(0编辑  收藏  举报

第一种:(原创)

 

/// <summary>
/// 内容替换
/// </summary>
/// <param name="input">内容</param>
/// <param name="oldValue">替换前的字符串</param>
/// <param name="newValue">替换后的字符串</param>
/// <param name="count">替换次数</param>
/// <returns></returns>
private string Replace(string input, string oldValue, string newValue, int count)
{
    if (input.IndexOf(oldValue) == -1)
        return input;

    int i = 0;
    StringBuilder sb = new StringBuilder();

    while (input.IndexOf(oldValue) != -1)
    {
        int index = input.IndexOf(oldValue);
        string temp = input.Substring(0, index + oldValue.Length);
        if (i++ < count)
        {
            temp = temp.Replace(oldValue, newValue);
            sb.Append(temp);
        }
        else
        {
            sb.Append(input);
            break;
        }
        input = input.Substring(index + oldValue.Length);
        if (input.IndexOf(oldValue) == -1)
        {
            sb.Append(input);
            break;
        }
    }

    return sb.ToString();
}

 

第二种:(来自CSDN,部分修改)

 

private string RegReplace(string input, string oldValue, string newValue, int count)
{
    int i = 0;
    return Regex.Replace(input, oldValue, new MatchEvaluator(delegate(Match match) { return i++ < count ? newValue : match.Value; }));
}