IT story

문자열의 주어진 색인에서 문자를 바꾸시겠습니까?

hot-time 2020. 7. 18. 10:01
반응형

문자열의 주어진 색인에서 문자를 바꾸시겠습니까? [복제]


이 질문에는 이미 답변이 있습니다.

String은을 가지고 있지 않으며 ReplaceAt()필요한 것을 수행하는 적절한 기능을 만드는 방법에 대해 약간 넘어지고 있습니다. CPU 비용이 높다고 가정하지만 문자열 크기가 작으므로 모두 괜찮습니다.


사용 StringBuilder:

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

간단한 방법 같은 것입니다 :

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

나는 갑자기이 일을해야했고이 주제를 발견했다. 그래서 이것은 내 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, ' ');

결국 .Net Framework 2를 사용해야했기 때문에 StringBuilder클래스 변형을 사용합니다 .


문자열은 변경할 수없는 개체이므로 문자열에서 지정된 문자를 바꿀 수 없습니다. 당신이 할 수있는 일은 주어진 문자를 교체하여 새로운 문자열을 만들 수 있다는 것입니다.

그러나 새 문자열을 작성하려면 StringBuilder를 사용하지 않는 것이 좋습니다.

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

//newS = "axc";

프로젝트 (.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;
        }
    }
  }
}

String 객체의 확장 메소드로 사용할 수 있습니다 .


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

참고 URL : https://stackoverflow.com/questions/9367119/replacing-a-char-at-a-given-index-in-string

반응형