이 문서에서는 기존 string을 수정하여 string를 생성하는 몇 가지 기술을 설명합니다. 설명된 모든 기술은 수정 결과를 새 string 개체로 반환합니다. 원래 문자열과 수정된 문자열이 고유 인스턴스임을 보여주기 위해 예제에서는 결과를 새 변수에 저장합니다. 각 예제를 실행할 때 수정 string 된 원본 string 및 새 항목을 검사할 수 있습니다.
이 문서에는 몇 가지 기술이 설명되어 있습니다. 기존 텍스트를 바꿀 수 있습니다. 패턴을 검색하고 일치하는 텍스트를 다른 텍스트로 바꿀 수 있습니다. 문자열을 문자 시퀀스로 처리할 수 있습니다. 공백을 제거하는 편리한 메서드를 사용할 수도 있습니다. 시나리오와 가장 일치하는 기술을 선택합니다.
텍스트 바꾸기
다음 코드는 기존 텍스트를 대체 텍스트로 바꿔서 새 문자열을 만듭니다.
string source = "The mountains are behind the clouds today.";
// Replace one substring with another with String.Replace.
// Only exact matches are supported.
var replacement = source.Replace("mountains", "peaks");
Console.WriteLine($"The source string is <{source}>");
Console.WriteLine($"The updated string is <{replacement}>");
앞의 코드는 이 변경할 수 없는 문자열 속성을 보여 줍니다. 이전 예제에서는 원래 문자열 source이 수정되지 않음을 확인할 수 있습니다. 이 메서드는 String.Replace 수정 내용이 포함된 새 string 항목을 만듭니다.
메서드는 Replace 문자열 또는 단일 문자를 바꿀 수 있습니다. 두 경우 모두 검색된 텍스트의 모든 항목이 바뀝니다. 다음 예제에서는 모든 '' 문자를 '_'로 바꿉니다.
string source = "The mountains are behind the clouds today.";
// Replace all occurrences of one char with another.
var replacement = source.Replace(' ', '_');
Console.WriteLine(source);
Console.WriteLine(replacement);
원본 문자열은 변경되지 않으며 새 문자열이 대체와 함께 반환됩니다.
공백 제거
선행 또는 후행 공백을 제거하려면 String.Trim, String.TrimStart, 및 String.TrimEnd 메서드를 사용할 수 있습니다. 다음 코드에서는 각 예제를 보여 줍니다. 원본 문자열은 변경되지 않습니다. 이러한 메서드는 수정된 내용이 포함된 새 문자열을 반환합니다.
// Remove trailing and leading white space.
string source = " I'm wider than I need to be. ";
// Store the results in a new string variable.
var trimmedResult = source.Trim();
var trimLeading = source.TrimStart();
var trimTrailing = source.TrimEnd();
Console.WriteLine($"<{source}>");
Console.WriteLine($"<{trimmedResult}>");
Console.WriteLine($"<{trimLeading}>");
Console.WriteLine($"<{trimTrailing}>");
텍스트 제거
메서드를 사용하여 String.Remove 문자열에서 텍스트를 제거할 수 있습니다. 이 메서드는 특정 인덱스에서 시작하는 지정된 문자 수를 제거합니다. 다음 예제에서는 다음 String.IndexOf 을 사용하여 Remove 문자열에서 텍스트를 제거하는 방법을 보여줍니다.
string source = "Many mountains are behind many clouds today.";
// Remove a substring from the middle of the string.
string toRemove = "many ";
string result = string.Empty;
int i = source.IndexOf(toRemove);
if (i >= 0)
{
result= source.Remove(i, toRemove.Length);
}
Console.WriteLine(source);
Console.WriteLine(result);
일치하는 패턴 바꾸기
정규식을 사용하여 텍스트 일치 패턴을 패턴으로 정의할 수 있는 새 텍스트로 바꿀 수 있습니다. 다음 예제에서는 클래스를 System.Text.RegularExpressions.Regex 사용하여 소스 문자열에서 패턴을 찾아 적절한 대문자로 바꿉다. 메서드는 Regex.Replace(String, String, MatchEvaluator, RegexOptions) 대체 논리를 인수 중 하나로 제공하는 함수를 사용합니다. 이 예제에서 해당 함수 LocalReplaceMatchCase 는 샘플 메서드 내에 선언된 로컬 함수 입니다.
LocalReplaceMatchCase 는 클래스를 System.Text.StringBuilder 사용하여 적절한 대문자로 대체 문자열을 작성합니다.
정규식은 알려진 텍스트가 아니라 패턴을 따르는 텍스트를 검색하고 바꾸는 데 가장 유용합니다. 자세한 내용은 C#의 검색 문자열을 참조하세요. 검색 패턴인 "the\s"는 "the"라는 단어와 공백 문자를 검색합니다. 패턴의 해당 부분은 원본 문자열의 "there"가 일치하지 않도록 합니다. 정규식 언어 요소에 대한 자세한 내용은 정규식 언어 - 빠른 참조를 참조하세요.
string source = "The mountains are still there behind the clouds today.";
// Use Regex.Replace for more flexibility.
// Replace "the" or "The" with "many" or "Many".
// using System.Text.RegularExpressions
string replaceWith = "many ";
source = System.Text.RegularExpressions.Regex.Replace(source, """the\s""", LocalReplaceMatchCase,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
Console.WriteLine(source);
string LocalReplaceMatchCase(System.Text.RegularExpressions.Match matchExpression)
{
// Test whether the match is capitalized
if (Char.IsUpper(matchExpression.Value[0]))
{
// Capitalize the replacement string
System.Text.StringBuilder replacementBuilder = new System.Text.StringBuilder(replaceWith);
replacementBuilder[0] = Char.ToUpper(replacementBuilder[0]);
return replacementBuilder.ToString();
}
else
{
return replaceWith;
}
}
메서드는 StringBuilder.ToString 개체의 내용이 포함된 변경할 수 없는 문자열을 StringBuilder 반환합니다.
개별 문자 수정
문자열에서 문자 배열을 생성하고 배열의 내용을 수정한 다음 배열의 수정된 내용에서 새 문자열을 만들 수 있습니다.
다음 예제에서는 문자열의 문자 집합을 바꾸는 방법을 보여 있습니다. 먼저 메서드를 String.ToCharArray() 사용하여 문자 배열을 만듭니다. IndexOf 메서드를 사용하여 "fox"라는 단어의 시작 인덱스를 찾습니다. 그 다음 세 문자는 다른 단어로 대체됩니다. 마지막으로 업데이트된 문자 배열에서 새 문자열이 생성됩니다.
string phrase = "The quick brown fox jumps over the fence";
Console.WriteLine(phrase);
char[] phraseAsChars = phrase.ToCharArray();
int animalIndex = phrase.IndexOf("fox");
if (animalIndex != -1)
{
phraseAsChars[animalIndex++] = 'c';
phraseAsChars[animalIndex++] = 'a';
phraseAsChars[animalIndex] = 't';
}
string updatedPhrase = new string(phraseAsChars);
Console.WriteLine(updatedPhrase);
프로그래밍 방식으로 문자열 콘텐츠 빌드
문자열은 변경할 수 없기 때문에 이전 예제에서는 모두 임시 문자열 또는 문자 배열을 만듭니다. 고성능 시나리오에서는 이러한 힙 할당을 방지하는 것이 좋습니다. .NET은 중간 임시 문자열 할당을 방지하면서 콜백을 통해 문자열의 문자 콘텐츠를 프로그래밍 방식으로 채울 수 있는 메서드를 제공합니다 String.Create .
// constructing a string from a char array, prefix it with some additional characters
char[] chars = [ 'a', 'b', 'c', 'd', '\0' ];
int length = chars.Length + 2;
string result = string.Create(length, chars, (Span<char> strContent, char[] charArray) =>
{
strContent[0] = '0';
strContent[1] = '1';
for (int i = 0; i < charArray.Length; i++)
{
strContent[i + 2] = charArray[i];
}
});
Console.WriteLine(result);
안전하지 않은 코드를 사용하여 고정 블록에서 문자열을 수정할 수 있지만, 문자열을 만든 후에는 문자열 콘텐츠를 수정하는 것이 강력히 권장되지 않습니다. 이렇게 하면 예측할 수 없는 버그가 발생합니다. 예를 들어, 다른 사람이 사용자와 동일한 콘텐츠를 가진 문자열을 메모리 절약을 위해 내부적으로 사용하게 되면, 그들은 사용자의 복사본을 얻게 됩니다. 이때, 사용자가 문자열을 수정할 것이라고 예상하지 못할 수 있습니다.
참고하십시오
.NET