用给定字符替换字符串字符

时间:2019-04-04 09:31:41

标签: c# string

我有一个包含字符和整数的长字符串。 我想将x,y,z ...索引上的字符替换为给定字符,例如:'

示例:将索引为3,9和14的字符替换为'

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

我正在寻找C#中的一些通用解决方案

2 个答案:

答案 0 :(得分:7)

最简单的选择可能是使用具有读/写索引器的StringBuilder

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();
    }
}

您当然可以通过char数组来做到这一点:

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

答案 1 :(得分:4)

您可以尝试 Linq

string input = "c9e49869a1483v4d9b4ab7d394a328d7d8a3";

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

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