Replacing a char at a given index in string?

C#String

C# Problem Overview


String does not have ReplaceAt(), and I'm tumbling a bit on how to make a decent function that does what I need. I suppose the CPU cost is high, but the string sizes are small so it's all ok

C# Solutions


Solution 1 - C#

Use a StringBuilder:

StringBuilder sb = new StringBuilder(theString);
sb[index] = newChar;
theString = sb.ToString();

Solution 2 - C#

The simplest approach would be something like:

public static string ReplaceAt(this string input, int index, char newChar)
{
    if (input == null)
    {
        throw new ArgumentNullException("input");
    }
    char[] chars = input.ToCharArray();
    chars[index] = newChar;
    return new string(chars);
}

This is now an extension method so you can use:

var foo = "hello".ReplaceAt(2, 'x');
Console.WriteLine(foo); // hexlo

It would be nice to think of some way that only required a single copy of the data to be made rather than the two here, but I'm not sure of any way of doing that. It's possible that this would do it:

public static string ReplaceAt(this string input, int index, char newChar)
{
    if (input == null)
    {
        throw new ArgumentNullException("input");
    }
    StringBuilder builder = new StringBuilder(input);
    builder[index] = newChar;
    return builder.ToString();
}

... I suspect it entirely depends on which version of the framework you're using.

Solution 3 - C#

string s = "ihj";
char[] array = s.ToCharArray();
array[1] = 'p';
s = new string(array);

Solution 4 - C#

Strings are immutable objects, so you can't replace a given character in the string. What you can do is you can create a new string with the given character replaced.

But if you are to create a new string, why not use a StringBuilder:

string s = "abc";
StringBuilder sb = new StringBuilder(s);
sb[1] = 'x';
string newS = sb.ToString();

//newS = "axc";

Solution 5 - C#

I suddenly needed to do this task and found this topic. So, this is my linq-style variant:

public static class Extensions
{
    public static string ReplaceAt(this string value, int index, char newchar)
    {
        if (value.Length <= index)
            return value;
        else
            return string.Concat(value.Select((c, i) => i == index ? newchar : c));
    }
}

and then, for example:

string instr = "Replace$dollar";
string outstr = instr.ReplaceAt(7, ' ');

In the end I needed to utilize .Net Framework 2, so I use a StringBuilder class variant though.

Solution 6 - C#

If your project (.csproj) allow unsafe code probably this is the faster solution:

namespace System
{
  public static class StringExt
  {
    public static unsafe void ReplaceAt(this string source, int index, char value)
    {
        if (source == null)
            throw new ArgumentNullException("source");

        if (index < 0 || index >= source.Length)
            throw new IndexOutOfRangeException("invalid index value");

        fixed (char* ptr = source)
        {
            ptr[index] = value;
        }
    }
  }
}

You may use it as extension method of String objects.

Solution 7 - C#

public string ReplaceChar(string sourceString, char newChar, int charIndex)
    {
        try
        {
            // if the sourceString exists
            if (!String.IsNullOrEmpty(sourceString))
            {
                // verify the lenght is in range
                if (charIndex < sourceString.Length)
                {
                    // Get the oldChar
                    char oldChar = sourceString[charIndex];

                    // Replace out the char  ***WARNING - THIS CODE IS WRONG - it replaces ALL occurrences of oldChar in string!!!***
                    sourceString.Replace(oldChar, newChar);
                }
            }
        }
        catch (Exception error)
        {
            // for debugging only
            string err = error.ToString();
        }

        // return value
        return sourceString;
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJason94View Question on Stackoverflow
Solution 1 - C#Thomas LevesqueView Answer on Stackoverflow
Solution 2 - C#Jon SkeetView Answer on Stackoverflow
Solution 3 - C#MaciejView Answer on Stackoverflow
Solution 4 - C#Petar IvanovView Answer on Stackoverflow
Solution 5 - C#horghView Answer on Stackoverflow
Solution 6 - C#dbvegaView Answer on Stackoverflow
Solution 7 - C#user1054326View Answer on Stackoverflow