Hexanix Hexanix - 8 months ago 22
C# Question

In C# - how can I take a specific char from a specific string, which is a part of an array of strings, and then replace it with another one?

For example I have the following code:

string Sheet[] = new string[]{

"abcdefg" };


Console.SetCursorPosition(0, 0);
Console.WriteLine(string.Join(Environment.NewLine, Sheet)); }

However, I want to replace 'C' with '#'.

Because the cycle constantly reprints the text sheet, setting the cursor position and overwriting the 'C' doesn't solve my problem. I thought maybe if I used the

string.replace(Oldchar, NewChar)

function it may work. My question is: How can I select the specific string from the array and then the specific char?

EDIT: I may have asked the question a bit too vaguely. What if there are more 'C' characters in that string, but I want to repalce the 'C' in that specific position? It doesn't have to be it's first occurance.


Strings are immutable in C#. This means you cannot change a string, but only create a new one from the old with specific changes.

For your case this means you have to replace all the strings in your array with new ones created by replacing C with # in the old ones

for(int i=0; i<Sheet.Length; i++) Sheet[i] = Sheet[i].Replace("C", "#");

or if you can replace the whole array:

Sheet = Sheet.Select(s => s.Replace("C", "#")).ToArray();

UPDATE: if you want to replace only a single character in a string, let's say the first occurence of 'C', you can do this:

for(int i=0; i<Sheet.Length; i++)
    string old = Sheet[i];
    int index = old.IndexOf('C');
    if (index < 0) continue; // no C in this string
    Sheet[i] = old.Remove(index, 1).Insert(index, "#");

So you remove the 1 characer and insert the new one.