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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9367119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:03:02  来源:igfitidea点击:

Replacing a char at a given index in string?

c#string

提问by Jason94

String does not have ReplaceAt(), and I'm tumbling a bit on how to make a decent function that does what I need. I suppose the CPU cost is high, but the string sizes are small so it's all ok

String 没有ReplaceAt(),我正在纠结如何制作一个满足我需要的体面的函数。我想 CPU 成本很高,但是字符串很小,所以没关系

采纳答案by Thomas Levesque

Use a StringBuilder:

使用StringBuilder

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

回答by Maciej

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

回答by Jon Skeet

The simplestapproach would be something like:

最简单的办法是这样的:

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

This is now an extension method so you can use:

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

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

It would be nice to think of some way that only required a singlecopy of the data to be made rather than the two here, but I'm not sure of any way of doing that. It's possiblethat this would do it:

想到一些只需要制作数据的一个副本而不是这里的两个副本的方法会很好,但我不确定有什么方法可以做到这一点。有可能这样做:

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

... I suspect it entirely depends on which version of the framework you're using.

...我怀疑这完全取决于您使用的框架版本。

回答by Petar Ivanov

Strings are immutable objects, so you can't replace a given character in the string. What you can do is you can create a new string with the given character replaced.

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

But if you are to create a new string, why not use a StringBuilder:

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

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

//newS = "axc";

回答by user1054326

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

回答by horgh

I suddenly needed to do this task and found this topic. So, this is my linq-style variant:

突然需要做这个任务,找到了这个话题。所以,这是我的 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));
    }
}

and then, for example:

然后,例如:

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

In the end I needed to utilize .Net Framework 2, so I use a StringBuilderclass variant though.

最后我需要使用 .Net Framework 2,所以我使用了一个StringBuilder类变体。

回答by dbvega

If your project (.csproj) allow unsafe code probably this is the faster solution:

如果您的项目 (.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;
        }
    }
  }
}

You may use it as extension method of Stringobjects.

您可以将其用作String对象的扩展方法。