开发者

replace the 2nd match skipping 1st match in C# [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 10 years ago.

i have a string which has 2 similar words..i want to replace the 2 secon开发者_C百科d word but not the 1st one..any help??


You could use regular expressions and a lookbehind.

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

This will replace all instances of the word "hello" with "goodbye", except for the first.


The Regex version is concise, but if you're not of the sort to use a regular expression, you could consider something more code heavy.

The StringBuilder class provides a way to replace within a given substring. In this extension method on string, we'll specify a substring that starts at the conclusion of the first applicable match. Some basic validation against arguments are in place, but I can't say I've tested all combinations.

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;
}

Using it:

string foobar = "foofoo".SkipReplace("foo", "bar");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜