替换第二场比赛在C#中跳过第一场比赛

时间:2011-04-27 03:52:56

标签: c# windows forms

我有一个字符串,其中有2个相似的单词..我想要替换2秒的单词而不是第1个单词。有什么帮助?

2 个答案:

答案 0 :(得分:1)

您可以使用正则表达式和lookbehind。

var replaceHello = "ABC hello 123 hello 456 hello 789";
var fixedUp = Regex.Replace(replaceHello, "(?<=hello.*)hello", "goodbye"); 

除了第一个以外,这将用“再见”替换“hello”一词的所有实例。

答案 1 :(得分:0)

Regex版本很简洁,但是如果你不是那种使用正则表达式的东西,你可以考虑更多的代码。

StringBuilder类提供了在给定子字符串中替换的方法。在string的这个扩展方法中,我们将指定一个从第一个适用匹配结束时开始的子字符串。一些针对参数的基本验证已经到位,但我不能说我已经测试了所有组合。

public static string SkipReplace(this string input, string oldValue, string newValue)
{
    if (input == null)
        throw new ArgumentNullException("input");

    if (string.IsNullOrEmpty(oldValue))
        throw new ArgumentException("oldValue");

    if (newValue == null)
        throw new ArgumentNullException("newValue");

    int index = input.IndexOf(oldValue);

    if (index > -1)
    {
        int startingPoint = index + oldValue.Length;
        int count = input.Length - startingPoint;
        StringBuilder builder = new StringBuilder(input);
        builder.Replace(oldValue, newValue, startingPoint, count);

        return builder.ToString();
    }

    return input;
}

使用它:

string foobar = "foofoo".SkipReplace("foo", "bar");
相关问题