简体   繁体   中英

assigning characters to a string in C#

public string simplifyString(string sInput)
{
        if (sInput.Length < 2)
        {
            return sInput;
        } 

        string sOutput;
        int iCount = 0;

        for (int i=1; i < sInput.Length; i++)
        {
            if (sInput[i] != sInput[iCount])
            {
                iCount++;
                sOutput[iCount] = sInput[i];
            }
        }
        return sOutput;
}

The precompiler has a problem with the above C# code.

sOutput[iCount] = sInput[i];

this line has an error. It says that string.this[int] cannot be assigned and is read only.

A string in .NET is immutable, once created it cannot be changed.

If you only need to replace characters (not remove or add) then you can simply convert it to an array before and back to a string afterwards:

var a = sOutput.ToCharArray();
// code that modifies a
var s = new string(a);

If you need to be able to remove or add as well, you can use a StringBuilder :

var sb = new StringBuilder(sOutput);
// code that modifies sb
var s = sb.ToString();

If you change your code to like below, I think your problem will be solved:

public string simplifyString(string sInput)
{
    if (sInput.Length < 2)
    {
        return sInput;
    } 

    string sOutput = sInput[0].ToString(); //Add initial for string
    int iCount = 0;

    for (int i=1; i < sInput.Length; i++)
    {
        if (sInput[i] != sInput[iCount])
        {
            iCount++;
            sOutput += sInput[i].ToString();//add new char as string to the end of the string
        }
    }
    return sOutput;
}

This is an area where budding c# programmers err! string is immutable in C#,ie, you can't modify a string in C# !

Each time you want to edit a portion of the string you need to create a new string object and provide it with the edited values. however if your program has too many of such operations it would be it would have a appreciable memory overhead ! all this memory won't be freed until the Garbage Collector of .net decides to run! If your string involves lot of editing operations use string builder!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM