Twi
Twi

Reputation: 825

Replace string characters with a given character

I have a long string which contains chars and integers. I would like to replace the character on the x,y,z... index to a given character like: '

Example: Replace chars to ' on index: 3,9 and 14

input:  c9e49869a1483v4d9b4ab7d394a328d7d8a3
output: c9e'9869a'483v'd9b4ab7d394a328d7d8a3 

I am looking for some generic solution in C#

Upvotes: 0

Views: 175

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499770

The simplest option is probably to use a StringBuilder, which has a read/write indexer:

using System;
using System.Text;

public class Test
{
    public static void Main()
    {
        string oldText = "c9e49869a1483v4d9b4ab7d394a328d7d8a3";
        string newText = ReplaceByIndex(oldText, '\'', 3, 9, 14);
        Console.WriteLine(newText);
    }

    static string ReplaceByIndex(string text, char newValue, params int[] indexes)
    {
        var builder = new StringBuilder(text);
        foreach (var index in indexes)
        {
            builder[index] = newValue;
        }
        return builder.ToString();
    }
}

You could do it via a char array instead, of course:

static string ReplaceByIndex(string text, char newValue, params int[] indexes)
{
    var array = text.ToCharArray();
    foreach (var index in indexes)
    {
        array[index] = newValue;
    }
    return new string(array);
}

Upvotes: 7

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

You can try Linq:

string input = "c9e49869a1483v4d9b4ab7d394a328d7d8a3";

int[] positions = new[] {4, 10, 15}; 

string output = string.Concat(input.Select((c, i) => positions.Contains(i) ? '\'' : c));

Upvotes: 4

Related Questions