You could use the StringBuilder class and the String.IndexOf method as follows:
Option 1
private static string ReplaceNthOccurrence(string input, int n, char find, char replaceWith) { int index = -1; int count = 0; StringBuilder sBuilder = new StringBuilder(input); while ((index = input.IndexOf(find, index + 1)) != -1) { if (++count == n) { sBuilder[index] = replaceWith; break; } } return sBuilder.ToString(); }
Usage:
string input = "Hi this is empty string. This should be in new line!"; string output = ReplaceNthOccurrence(input , 5, ' ', '\n');
The StringBuilder class allows us to replace a particular char in the string by its index.
The String.IndexOf method allows us to fast search for a desired char in the string.
Option 2
private static string ReplaceNthOccurrence(string input, int n, char find, char replaceWith) { int index = -1; // Loop for `n` occurrences: for (int count = 0; count < n; count++) { // Find a position of the next occurrence: index = input.IndexOf(find, index + 1); // If not found, return the `input` string: if (index == -1) return input; } // Replace the char and return a resulting string: StringBuilder sBuilder = new StringBuilder(input); sBuilder[index] = replaceWith; return sBuilder.ToString(); }
In the latter option, you can use any other replacement approach instead of the StringBuilder.
For instance:
return input.Substring(0, index) + replaceWith + input.Substring(index + 1);