how do I set a character at an index in a string in c#?

后端 未结 7 1260
生来不讨喜
生来不讨喜 2020-11-28 16:28
someString[someRandomIdx] = \'g\';

will give me an error.

How do I achieve the above?

相关标签:
7条回答
  • 2020-11-28 16:49

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

    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));
    
    0 讨论(0)
  • 2020-11-28 16:50

    Since no one mentioned a one-liner solution:

    someString = someString.Remove(index, 1).Insert(index, "g");
    
    0 讨论(0)
  • 2020-11-28 16:51

    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 讨论(0)
  • 2020-11-28 17:03

    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.
    0 讨论(0)
  • 2020-11-28 17:06

    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)
                    {
                    }
                }
            }
    
    0 讨论(0)
  • 2020-11-28 17:11

    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.
    
    0 讨论(0)
提交回复
热议问题