String类中没有ReplaceAt()
方法,我需要一个能够满足我的需求的函数,但是我有点不确定该如何实现。虽然这可能会导致CPU开销较大,但是由于字符串大小很小,所以这并不成问题。
StringBuilder
:StringBuilder sb = new StringBuilder(theString);
sb[index] = newChar;
theString = sb.ToString();
new StringBuilder(theString) {[index] = newChar}.ToString();
- Teun最简单的方法可能是这样的:
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();
}
我认为这完全取决于你正在使用的框架版本。
string s = "ihj";
char[] array = s.ToCharArray();
array[1] = 'p';
s = new string(array);
字符串是不可变对象,因此您无法替换字符串中的某个字符。 您可以做的是创建一个用给定字符替换的新字符串。
但是,如果要创建一个新字符串,为什么不使用 StringBuilder:
string s = "abc";
StringBuilder sb = new StringBuilder(s);
sb[1] = 'x';
string newS = sb.ToString();
//newS = "axc";
我突然需要完成这个任务,然后发现了这个主题。所以,这是我的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, ' ');
StringBuilder
或ToCharArray
解决方案呢?虽然相比于StringBuilder
可能少了一次字符串复制,但我怀疑内部会发生很多事情。 - ToolmakerStevenamespace 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;
}
}
}
}
您可以将其用作 String 对象的扩展方法。
string
的语义 - 影响了对该对象的任何其他引用,从而使 string
对象 不可变 的文档无效/相矛盾。对一个内置类这样做是极不可靠的(强烈的代码味道)。需要在其上添加巨大的警告注释。就我个人而言,我不会这样做。如果有人需要一个可变的字符串,则应创建一个适当的类,子类或包装一个char []
。 - ToolmakerStevepublic 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;
}