C에서 문자열 내용 수정#

Tip

이 문서는 이미 하나 이상의 프로그래밍 언어를 알고 있으며 C#을 학습하는 개발자를 위한 기본 사항 섹션의 일부입니다. 프로그래밍을 처음 접하는 경우 먼저 시작 자습서로 시작 하세요.

다른 언어에서 오시겠습니까? Java 및 JavaScript와 마찬가지로 C# 문자열은 변경할 수 없습니다. 원래 문자열을 변경하는 대신 새 문자열과 같은 Replace 메서드를 Trim 반환합니다. 여기에 있는 패턴은 해당 언어의 병렬 String 메서드입니다.

C#은 string. 즉, C# 을 만든 후에는 해당 내용이 변경되지 않습니다. 문자열을 수정하는 것처럼 보이는 모든 메서드는 변경 내용이 포함된 새 string 메서드를 실제로 반환하며 원래 메서드는 그대로 유지됩니다. 이 문서의 예제에서는 원본 값과 수정된 값을 모두 볼 수 있도록 각 결과를 새 변수로 저장합니다.

알려진 텍스트 바꾸기, 공백 자르기, 문자 범위 제거, 패턴과 일치하는 텍스트 바꾸기 또는 개별 문자 편집과 같은 시나리오와 일치하는 기술을 선택합니다.

알려진 텍스트 바꾸기

이 메서드는 String.Replace 한 문자열의 모든 항목을 다른 문자열로 대체하고 결과를 새 문자열로 반환합니다.

string source = "The mountains are behind the clouds today.";

// Replace returns a new string; the original is unchanged.
string updated = source.Replace("mountains", "peaks");

Console.WriteLine(source);
// => The mountains are behind the clouds today.
Console.WriteLine(updated);
// => The peaks are behind the clouds today.

원래 문자열은 변경되지 않습니다. 이는 불변성을 Replace 보여 줍니다. 대체를 사용하여 새 문자열을 만듭니다.

Replace 또한 단일 문자를 교환하는 오버로드가 있습니다. 다음 예제에서는 모든 공간을 밑줄로 바꿉니다.

string source = "The mountains are behind the clouds today.";

// Replace every occurrence of one character with another.
string updated = source.Replace(' ', '_');

Console.WriteLine(updated);
// => The_mountains_are_behind_the_clouds_today.

두 오버로드 모두 문자열에서 첫 번째 일치 항목만 대체하는 것이 아니라 모든 일치 항목을 대체합니다. 단일 문자 또는 문자열 Replace 을 전달하든 관계없이 한 번의 호출에서 모든 항목을 대체합니다.

공백 자르기

선행 또는 후행 공백을 제거하려면 String.Trim, String.TrimStart, 및 String.TrimEnd를 사용하세요. 각 메서드는 새 문자열을 반환합니다.

string source = "    I'm wider than I need to be.      ";

// Each method returns a new string with whitespace removed.
Console.WriteLine($"<{source.Trim()}>");
// => <I'm wider than I need to be.>
Console.WriteLine($"<{source.TrimStart()}>");
// => <I'm wider than I need to be.      >
Console.WriteLine($"<{source.TrimEnd()}>");
// => <    I'm wider than I need to be.>

문자 구간 삭제

이 메서드는 String.Remove 인덱스에서 시작하는 여러 문자를 삭제합니다. String.IndexOf와 결합하여 제거할 텍스트를 찾습니다.

string source = "Many mountains are behind many clouds today.";
string toRemove = "many ";

// Find the text, then remove that span by index and length.
int index = source.IndexOf(toRemove);
string result = index >= 0
    ? source.Remove(index, toRemove.Length)
    : source;

Console.WriteLine(result);
// => Many mountains are behind clouds today.

패턴과 일치하는 텍스트 바꾸기

정확한 문자열이 아닌 패턴 뒤에 있는 텍스트를 바꾸어야 하는 경우 정규식을 사용합니다. 이 메서드는 Regex.Replace 각 대체를 계산하는 함수를 허용하므로 원래 대문자화와 같은 세부 정보를 유지할 수 있습니다. 패턴 the\s은 공백 문자가 뒤따르는 "the"와 일치하므로, 따라서 "there"와는 일치하지 않습니다.

string source = "The mountains are still there behind the clouds today.";

// Replace "the" or "The" followed by whitespace, preserving the original case.
// The \s in the pattern keeps "there" from matching.
string result = Regex.Replace(
    source,
    """the\s""",
    match => char.IsUpper(match.Value[0]) ? "Many " : "many ",
    RegexOptions.IgnoreCase);

Console.WriteLine(result);
// => Many mountains are still there behind many clouds today.

대체가 아닌 패턴 기반 검색은 C#의 검색 문자열을 참조하세요. 정규식 구문은 정규식 언어 빠른 참조를 참조하세요.

개별 문자 수정

위치별로 문자를 변경하려면 문자열을 문자 Span<T>에 복사한 다음 span을 수정하고, 그로부터 새 문자열을 빌드합니다. 다음 예제에서는 "fox"라는 단어를 찾아서 "cat"로 바꿉니다.

string phrase = "The quick brown fox jumps over the fence.";

// A string is immutable, so copy it into a Span<char> to edit in place.
Span<char> characters = stackalloc char[phrase.Length];
phrase.CopyTo(characters);
int index = phrase.IndexOf("fox");
if (index != -1)
{
    characters[index] = 'c';
    characters[index + 1] = 'a';
    characters[index + 2] = 't';
}

// Build a new string from the modified characters.
string updated = new string(characters);
Console.WriteLine(updated);
// => The quick brown cat jumps over the fence.

중간 할당을 방지하는 고성능 시나리오의 경우 런타임은 다음과 같은 String.Create하위 수준 API를 제공합니다. 이러한 기술은 고급입니다. 일상적인 코드의 경우 이 문서의 메서드가 올바른 선택입니다.

참고하십시오