다음을 통해 공유


방법: 문자열 내용 수정(C# 프로그래밍 가이드)

문자열은 변경 불가능하므로 문자열 개체를 만든 후에 안전하지 않은 코드를 사용하지 않고 문자열 개체의 값을 수정할 수는 없습니다.하지만 문자열 값을 수정하여 그 결과를 새 문자열 개체에 저장하는 방법은 많습니다.System.String 클래스는 입력 문자열을 처리하여 새 문자열 개체를 반환하는 메서드를 제공합니다.많은 경우 새 개체를 원래 문자열을 유지하는 변수에 할당할 수 있습니다.System.Text.RegularExpressions.Regex 클래스는 유사한 방식으로 작동하는 추가 메서드를 제공합니다.System.Text.StringBuilder 클래스는 "내부"에서 수정할 수 있는 문자 버퍼를 제공합니다. StringBuilder.ToString 메서드를 호출하여 버퍼의 현재 내용을 포함하는 새 문자열 개체를 만들 수 있습니다.

예제

다음 예제에서는 지정된 문자열에서 부분 문자열을 바꾸거나 제거하는 다양한 방법을 보여 줍니다.

class ReplaceSubstrings
{
    string searchFor;
    string replaceWith;

    static void Main(string[] args)
    {

        ReplaceSubstrings app = new ReplaceSubstrings();
        string s = "The mountains are behind the clouds today.";

        // Replace one substring with another with String.Replace.
        // Only exact matches are supported.
        s = s.Replace("mountains", "peaks");
        Console.WriteLine(s);
        // Output: The peaks are behind the clouds today.

        // Use Regex.Replace for more flexibility. 
        // Replace "the" or "The" with "many" or "Many".
        // using System.Text.RegularExpressions
        app.searchFor = "the"; // A very simple regular expression.
        app.replaceWith = "many";
        s = Regex.Replace(s, app.searchFor, app.ReplaceMatchCase, RegexOptions.IgnoreCase);
        Console.WriteLine(s);
        // Output: Many peaks are behind many clouds today.

        // Replace all occurrences of one char with another.
        s = s.Replace(' ', '_');
        Console.WriteLine(s);
        // Output: Many_peaks_are_behind_many_clouds_today.

        // Remove a substring from the middle of the string.
        string temp = "many_";
        int i = s.IndexOf(temp);
        if (i >= 0)
        {
            s = s.Remove(i, temp.Length);
        }
        Console.WriteLine(s);
        // Output: Many_peaks_are_behind_clouds_today.

        // Remove trailing and leading whitespace.
        // See also the TrimStart and TrimEnd methods.
        string s2 = "    I'm wider than I need to be.      ";
        // Store the results in a new string variable.
        temp = s2.Trim();
        Console.WriteLine(temp);
        // Output: I'm wider than I need to be.

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }

    // Custom match method called by Regex.Replace
    // using System.Text.RegularExpressions
    string ReplaceMatchCase(Match m)
    {
        // Test whether the match is capitalized
        if (Char.IsUpper(m.Value[0]) == true)
        {
            // Capitalize the replacement string
            // using System.Text;
            StringBuilder sb = new StringBuilder(replaceWith);
            sb[0] = (Char.ToUpper(sb[0]));
            return sb.ToString();
        }
        else
        {
            return replaceWith;
        }
    }
}

배열 표기법을 사용하여 문자열의 개별 문자에 액세스하려면 StringBuilder 개체를 사용합니다. 이 개체를 사용하면 [] 연산자를 오버로드하여 개체의 내부 문자 버퍼에 액세스할 수 있습니다.ToCharArray 메서드를 사용하면 문자열을 문자 배열로 변환할 수도 있습니다.다음 예제에서는 ToCharArray를 사용하여 배열을 만듭니다.그런 다음 이 배열의 요소 일부를 수정합니다.계속해서, 문자 배열을 입력 매개 변수로 사용하는 문자열 생성자가 호출되어 새 문자열이 만들어집니다.

class ModifyStrings
{
    static void Main()
    {
        string str = "The quick brown fox jumped over the fence";
        System.Console.WriteLine(str);

        char[] chars = str.ToCharArray();
        int animalIndex = str.IndexOf("fox");
        if (animalIndex != -1)
        {
            chars[animalIndex++] = 'c';
            chars[animalIndex++] = 'a';
            chars[animalIndex] = 't';
        }

        string str2 = new string(chars);
        System.Console.WriteLine(str2);

        // Keep the console window open in debug mode
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/* Output:
  The quick brown fox jumped over the fence
  The quick brown cat jumped over the fence 
*/

다음 예제에서는 C 스타일의 문자 배열과 유사한 방식으로 안전하지 않은 코드를 사용하여 문자열을 내부적으로 수정해야 하는 매우 드문 경우를 보여 줍니다.이 예제에서는 fixed 키워드를 사용하여 개별 문자에 "내부적으로" 액세스하는 방법을 보여 줍니다.또한 C# 컴파일러가 내부적으로 문자열을 저장하는 방식 때문에 문자열에 대한 안전하지 않은 작업에서 발생할 수 있는 부작용에 대해서도 설명합니다.일반적으로 반드시 필요한 경우가 아니라면 이 방법을 사용해서는 안 됩니다.

class UnsafeString
{
    unsafe static void Main(string[] args)
    {
        // Compiler will store (intern) 
        // these strings in same location.
        string s1 = "Hello";
        string s2 = "Hello";

        // Change one string using unsafe code.
        fixed (char* p = s1)
        {
            p[0] = 'C';
        }

        //  Both strings have changed.
        Console.WriteLine(s1);
        Console.WriteLine(s2);

        // Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

}

참고 항목

개념

C# 프로그래밍 가이드

기타 리소스

문자열(C# 프로그래밍 가이드)