matt
matt

Reputation: 4244

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

someString[someRandomIdx] = 'g';

will give me an error.

How do I achieve the above?

Upvotes: 47

Views: 49354

Answers (8)

Vanden
Vanden

Reputation: 1

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-----'

Upvotes: 0

Lily Finley
Lily Finley

Reputation: 3017

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

Upvotes: 0

ajay_whiz
ajay_whiz

Reputation: 17931

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

Upvotes: -2

polfosol ఠ_ఠ
polfosol ఠ_ఠ

Reputation: 1898

Since no one mentioned a one-liner solution:

someString = someString.Remove(index, 1).Insert(index, "g");

Upvotes: 7

Alexey Zadorozhny
Alexey Zadorozhny

Reputation: 31

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)
                {
                }
            }
        }

Upvotes: 3

Matt Ellen
Matt Ellen

Reputation: 11592

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.

Upvotes: 71

advait
advait

Reputation: 6525

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.

Upvotes: 1

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421978

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.

Upvotes: 42

Related Questions