Search code examples
c#listenumerationflat-file

Replace character at specific index in List<string>, but indexer is read only


This is kind of a basic question, but I learned programming in C++ and am just transitioning to C#, so my ignorance of the C# methods are getting in my way.

A client has given me a few fixed length files and they want the 484th character of every odd numbered record, skipping the first one (3, 5, 7, etc...) changed from a space to a 0. In my mind, I should be able to do something like the below:

static void Main(string[] args)
{
    List<string> allLines = System.IO.File.ReadAllLines(@"C:\...").ToList();

    foreach(string line in allLines)
    {
        //odd numbered logic here
        line[483] = '0';
    }
...
//write to new file
}

However, the property or indexer cannot be assigned to because it is read only. All my reading says that I have not set a setter for the variable, and I have tried what was shown at this SO article, but I am doing something wrong every time. Should what is shown in that article work? Should I do something else?


Solution

  • You cannot modify C# strings directly, because they are immutable. You can convert strings to char[], modify it, then make a string again, and write it to file:

    File.WriteAllLines(
        @"c:\newfile.txt"
    ,   File.ReadAllLines(@"C:\...").Select((s, index) => {
            if (index % 2 = 0) {
                return s; // Even strings do not change
            }
            var chars = s.ToCharArray();
            chars[483] = '0';
            return new string(chars);
        })
    );