我有一个长字符串,包含字符和整数。我想替换x,y,z上的字符.对给定字符的索引,如:‘
示例:将chars替换为“on index: 3、9和14”
input: c9e49869a1483v4d9b4ab7d394a328d7d8a3
output: c9e'9869a'483v'd9b4ab7d394a328d7d8a3 我正在寻找C#中的一些通用解决方案
发布于 2019-04-04 09:35:07
最简单的选择可能是使用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);
}发布于 2019-04-04 09:34:58
你可以试试Linq
string input = "c9e49869a1483v4d9b4ab7d394a328d7d8a3";
int[] positions = new[] {4, 10, 15};
string output = string.Concat(input.Select((c, i) => positions.Contains(i) ? '\'' : c));https://stackoverflow.com/questions/55512490
复制相似问题