12

How to replace a string in a string except first occurrence?

e.g. C:\\Test-Processed\1-Processed\2-Processed should output

C:\\Test-Processed\1\2

5 Answers 5

12

Something like following:

string originalStr = "C:\\Test-Processed\\1-Processed\\2-Processed";
string temp = "-Processed";
string str = originalStr.Substring(0, originalStr.IndexOf(temp) + temp.Length);
originalStr = str + originalStr.Substring(str.Length).Replace(temp, "");

originalStr will be:

originalStr = "C:\\Test-Processed\\1\\2"
Sign up to request clarification or add additional context in comments.

Comments

5

The key insight here is the existence of an indexOf that starts searching the string at a certain point into the string, rather than from the start. Here: http://msdn.microsoft.com/en-us/library/7cct0x33.aspx

First off, you want to use .indexOf("-Processed") to find the first index of -Processed in the string. Remember this index.

Now, use .indexOf("-Processed", index+1) to find the next index of -Processed that is not the first.

Repeated that and Substring(nextindex, "-Processed".Length) to remove these extra instances until you find no more.

Comments

4
string ReplaceExceptFirst(string text, string search, string replace)
{
    int pos = text.IndexOf(search);
    if (pos < 0)
    {
        return text;
    }

    int strlen = pos + search.Length;
    return text.Substring(0, strlen) +  (text.Substring(strlen)).Replace(search,replace);
}

Comments

3

Something like so:

String str = @"C:\\Test-Processed\1-Processed\2-Processed";
System.Console.WriteLine(new Regex("(\\d+)-Processed").Replace(str, "$1"));

will yield C:\\Test-Processed\1\2. The regular expression assumes that the elements you want to remove are always preceded by one or more digits. It will put those digits in a capture group and replace the sub string (example 1-Processed) with only the digit (1).

EDIT: If the assumption fails, you might want to take the approach @Patashu suggested.

Comments

1

This is one of the solutions given above. (Solution by Habib and parameter naming by Pintu Paul). I used it but then defined the function as a String Extension.


public static class StringExtensions
{
    public static string ReplaceAllButFirst(this string originalStr, string search, string replace)
    {
        string str = originalStr.Substring(0, originalStr.IndexOf(search, System.StringComparison.InvariantCultureIgnoreCase) + search.Length);
        return str + originalStr.Substring(str.Length).Replace(search, replace);  
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.