替换字符串中给定索引处的字符?

字符串没有 ReplaceAt(),我在如何创建一个像样的函数来满足我的需要方面有些困难。我认为 CPU 的成本很高,但字符串的大小很小,所以一切都没问题

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

最简单的的做法类似于:

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

这现在是一个扩展方法,因此您可以使用:

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

如果能想到一种方法,只需要一个 单身数据副本,而不是这里的两个副本,那就太好了,但我不确定有什么方法可以做到这一点。有可能就是这样做的:

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

我怀疑这完全取决于你使用的是哪个版本的框架。

使用 StringBuilder:

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

字符串是不可变的对象,因此不能替换字符串中的给定字符。 您可以做的是创建一个新字符串,并替换给定的字符。

但是,如果要创建新字符串,为什么不使用 StringBuilder:

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


//newS = "axc";
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;
}

我突然需要做这个任务,找到了这个主题。 这是我的 linq 风格变体:

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

然后,例如:

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

最后,我需要利用.NetFramework2,所以我使用了 StringBuilder类的变体。

如果您的项目(. csproj)允许不安全的代码,这可能是更快的解决方案:

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

您可以使用它作为 绳子对象的扩展方法。