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
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"
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.
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.
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);
}
}