C# -Replace First and Last occurrence of certain string
Example:
string mystring = "123xyz123asd123rea";
In the above string the value 123 was repeated thrice, now we will see how to replace the first and last occurrence of value "123" with custom value.
public static string ReplaceFirstOccurence(string originalValue, string occurenceValue, string newValue)
{
if (string.IsNullOrEmpty(originalValue))
return string.Empty;
if (string.IsNullOrEmpty(occurenceValue))
return originalValue;
if (string.IsNullOrEmpty(newValue))
return originalValue;
int startindex = originalValue.IndexOf(occurenceValue);
return originalValue.Remove(startindex, occurenceValue.Length).Insert(startindex, newValue);
}
public static string ReplaceLastOccurence(string originalValue, string occurenceValue, string newValue)
{
if (string.IsNullOrEmpty(originalValue))
return string.Empty;
if (string.IsNullOrEmpty(occurenceValue))
return originalValue;
if (string.IsNullOrEmpty(newValue))
return originalValue;
int startindex = originalValue.LastIndexOf(occurenceValue);
return originalValue.Remove(startindex, occurenceValue.Length).Insert(startindex, newValue);
}
In the above example, we just finding the start index of the value, removing those value and inserting the new value.
Hope it helps......