[C#] String의 N번째 문자를 Replace하는 방법

less than 1 minute read

String의 N번째 문자를 Replace하는 방법

Reference

Problem

  • String의 N번째 문자를 string[index] = '{newChar}'로 바꾸려고 하니, Property or indexer string.this[int]' cannot be assigned to (it is read-only) 오류가 발생

Solution

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

Categories:

Updated:

Comments