47
someString[someRandomIdx] = 'g';

will give me an error.

How do I achieve the above?

3

8 Answers 8

69

If it is of type string then you can't do that because strings are immutable - they cannot be changed once they are set.

To achieve what you desire, you can use a StringBuilder

StringBuilder someString = new StringBuilder("someString");

someString[4] = 'g';

Update

Why use a string, instead of a StringBuilder? For lots of reasons. Here are some I can think of:

  • Accessing the value of a string is faster.
  • strings can be interned (this doesn't always happen), so that if you create a string with the same value then no extra memory is used.
  • strings are immutable, so they work better in hash based collections and they are inherently thread safe.
3
  • what is the difference between a string and a StringBuilder? i.e. why wouldn't I just use StringBuilders everywhere?
    – matt
    Commented Jul 22, 2010 at 7:37
  • for more information on the StringBuilder class: msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx
    – Matt Ellen
    Commented Jul 22, 2010 at 8:01
  • @matt string is immutable while StringBuilder is mutable and they have huge performance difference when you intend to modify a given string. Please read this and this for more details.
    – RBT
    Commented Jun 5, 2018 at 15:09
42

C# strings are immutable. You should create a new string with the modified contents.

 char[] charArr = someString.ToCharArray();
 charArr[someRandomIdx] = 'g'; // freely modify the array
 someString = new string(charArr); // create a new string with array contents.
7

Since no one mentioned a one-liner solution:

someString = someString.Remove(index, 1).Insert(index, "g");
5
  • 1
    Strings are immutable, therefore a method always returns a new string. You'll get a new string from the call to remove and then an additional string from insert. Use Matt Ellen's answer instead. Commented Apr 23, 2020 at 22:28
  • 1
    @Ruhrpottpatriot do you really think I didn't know that? Sometimes the performance is not a heavy barrier, so if a one-liner can get the job done, a lot of people won't bother writing a separate extension method and such. Commented Apr 24, 2020 at 15:25
  • 2
    You might know that, but others might not. Depending on the string size this can incur a heavy penalty, which you completely fail to mention. Your method is objectively worse than the accepted answer. And no, the readability between one or two lines of code isn't that big that you can bring up that as an argument. Commented May 6, 2020 at 13:09
  • @Ruhrpottpatriot and by the way, ToCharArray() is way faster than StringBuilder. The others —who you are concerned with shouldn't use Matt Ellen's answer either, since the one Mehrdad Afshari proposed is more efficient. See this comment. Commented May 6, 2020 at 13:40
  • A char array is faster, that is correct (and with greater length the advantage shrinks considerably according to my own tests), but that doesn't have anything to do with your code, which we talked about. Commented May 7, 2020 at 22:55
3

If you absolutely must change the existing instance of a string, there is a way with unsafe code:

        public static unsafe void ChangeCharInString(ref string str, char c, int index)
        {
            GCHandle handle;
            try
            {
                handle = GCHandle.Alloc(str, GCHandleType.Pinned);
                char* ptr = (char*)handle.AddrOfPinnedObject();
                ptr[index] = c;
            }
            finally
            {
                try
                {
                    handle.Free();
                }
                catch(InvalidOperationException)
                {
                }
            }
        }
1
  • 2
    Good to know this, thank you, but please don't make it this way :)
    – Roberto
    Commented Dec 13, 2016 at 21:50
1

Check out this article on how to modify string contents in C#. Strings are immutable so they must be converted into intermediate objects before they can be modified.

0

If you're willing to introduce Also(...):

public static class Ext
{
    public static T Also<T>(this T arg, Action<T> act) 
    { 
        act(arg); return arg; 
    }

    public static string ReplaceCharAt(this string str, int index, char replacement) => 
        new string(str.ToCharArray().Also(arr => arr[index] = replacement));
}

Which can be used as:

void Main()
{
    string str = "This is string";
    Console.WriteLine(str);
    
    var str2 = str.ReplaceCharAt(0,'L').ReplaceCharAt(1,'i').ReplaceCharAt(2,'l').ReplaceCharAt(3,'y');
    Console.WriteLine(str2);
}

To get the following output:

enter image description here

0

In addition to ajay_whiz answer:

    StringBuilder line = new StringBuilder("".PadRight(40));
    line.Insert(0, "hello"); // len 45
    line.Insert(5, "WORLD"); // len 50

    string rec = new string('-', 20)
    rec = rec.Insert(0, "HELLO"); // len 25
    rec = rec.Insert(10, "world"); // len 30
    // this string is len=30 and content 'HELLO-----world---------------'
    rec = rec.Substring(0, 20); // OKAY : 'HELLO-----world-----'
-2

you can also use Insert() method e.g. somestring.Insert(index,data)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.