StringInfo 클래스

정의

문자열을 텍스트 요소로 분할하고 해당 텍스트 요소를 통해 반복하는 기능을 제공합니다.

public ref class StringInfo
public class StringInfo
[System.Serializable]
public class StringInfo
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class StringInfo
type StringInfo = class
[<System.Serializable>]
type StringInfo = class
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type StringInfo = class
Public Class StringInfo
상속
StringInfo
특성

예제

이 예제에서는 클래스의 GetTextElementEnumeratorParseCombiningCharacters 메서드를 StringInfo 사용하여 서로게이트 및 결합 문자를 포함하는 문자열을 조작합니다.

using namespace System;
using namespace System::Text;
using namespace System::Globalization;


// Show how to enumerate each real character (honoring surrogates)
// in a string.

void EnumTextElements(String^ combiningChars)
{
    // This StringBuilder holds the output results.
    StringBuilder^ sb = gcnew StringBuilder();

    // Use the enumerator returned from GetTextElementEnumerator
    // method to examine each real character.
    TextElementEnumerator^ charEnum =
        StringInfo::GetTextElementEnumerator(combiningChars);
    while (charEnum->MoveNext())
    {
        sb->AppendFormat("Character at index {0} is '{1}'{2}", 
            charEnum->ElementIndex, charEnum->GetTextElement(), 
            Environment::NewLine);
    }

    // Show the results.
    Console::WriteLine("Result of GetTextElementEnumerator:");
    Console::WriteLine(sb);
}


// Show how to discover the index of each real character
// (honoring surrogates) in a string.

void EnumTextElementIndexes(String^ combiningChars)
{
    // This StringBuilder holds the output results.
    StringBuilder^ sb = gcnew StringBuilder();

    // Use the ParseCombiningCharacters method to
    // get the index of each real character in the string.
    array <int>^ textElemIndex =
        StringInfo::ParseCombiningCharacters(combiningChars);

    // Iterate through each real character showing the character
    // and the index where it was found.
    for (int i = 0; i < textElemIndex->Length; i++)
    {
        sb->AppendFormat("Character {0} starts at index {1}{2}",
            i, textElemIndex[i], Environment::NewLine);
    }

    // Show the results.
    Console::WriteLine("Result of ParseCombiningCharacters:");
    Console::WriteLine(sb);
}

int main()
{

    // The string below contains combining characters.
    String^ combiningChars = L"a\u0304\u0308bc\u0327";

    // Show each 'character' in the string.
    EnumTextElements(combiningChars);

    // Show the index in the string where each 'character' starts.
    EnumTextElementIndexes(combiningChars);

};

// This code produces the following output.
//
// Result of GetTextElementEnumerator:
// Character at index 0 is 'a-"'
// Character at index 3 is 'b'
// Character at index 4 is 'c,'
//
// Result of ParseCombiningCharacters:
// Character 0 starts at index 0
// Character 1 starts at index 3
// Character 2 starts at index 4
using System;
using System.Text;
using System.Globalization;

public sealed class App {
   static void Main() {
      // The string below contains combining characters.
      String s = "a\u0304\u0308bc\u0327";

      // Show each 'character' in the string.
      EnumTextElements(s);

      // Show the index in the string where each 'character' starts.
      EnumTextElementIndexes(s);
   }

   // Show how to enumerate each real character (honoring surrogates) in a string.
   static void EnumTextElements(String s) {
      // This StringBuilder holds the output results.
      StringBuilder sb = new StringBuilder();

      // Use the enumerator returned from GetTextElementEnumerator
      // method to examine each real character.
      TextElementEnumerator charEnum = StringInfo.GetTextElementEnumerator(s);
      while (charEnum.MoveNext()) {
         sb.AppendFormat(
           "Character at index {0} is '{1}'{2}",
           charEnum.ElementIndex, charEnum.GetTextElement(),
           Environment.NewLine);
      }

      // Show the results.
      Console.WriteLine("Result of GetTextElementEnumerator:");
      Console.WriteLine(sb);
   }

   // Show how to discover the index of each real character (honoring surrogates) in a string.
   static void EnumTextElementIndexes(String s) {
      // This StringBuilder holds the output results.
      StringBuilder sb = new StringBuilder();

      // Use the ParseCombiningCharacters method to
      // get the index of each real character in the string.
      Int32[] textElemIndex = StringInfo.ParseCombiningCharacters(s);

      // Iterate through each real character showing the character and the index where it was found.
      for (Int32 i = 0; i < textElemIndex.Length; i++) {
         sb.AppendFormat(
            "Character {0} starts at index {1}{2}",
            i, textElemIndex[i], Environment.NewLine);
      }

      // Show the results.
      Console.WriteLine("Result of ParseCombiningCharacters:");
      Console.WriteLine(sb);
   }
}

// This code produces the following output:
//
// Result of GetTextElementEnumerator:
// Character at index 0 is 'ā̈'
// Character at index 3 is 'b'
// Character at index 4 is 'ç'
//
// Result of ParseCombiningCharacters:
// Character 0 starts at index 0
// Character 1 starts at index 3
// Character 2 starts at index 4
Imports System.Text
Imports System.Globalization

Public Module Example
   Public Sub Main()
      ' The string below contains combining characters.
      Dim s As String = "a" + ChrW(&h0304) + ChrW(&h0308) + "bc" + ChrW(&h0327)

      ' Show each 'character' in the string.
      EnumTextElements(s)

      ' Show the index in the string where each 'character' starts.
      EnumTextElementIndexes(s)
   End Sub

   ' Show how to enumerate each real character (honoring surrogates) in a string.
   Sub EnumTextElements(s As String)
      ' This StringBuilder holds the output results.
      Dim sb As New StringBuilder()

      ' Use the enumerator returned from GetTextElementEnumerator 
      ' method to examine each real character.
      Dim charEnum As TextElementEnumerator = StringInfo.GetTextElementEnumerator(s)
      Do While charEnum.MoveNext()
         sb.AppendFormat("Character at index {0} is '{1}'{2}",
                         charEnum.ElementIndex, 
                         charEnum.GetTextElement(),
                         Environment.NewLine)
      Loop

      ' Show the results.
      Console.WriteLine("Result of GetTextElementEnumerator:")
      Console.WriteLine(sb)
   End Sub

   ' Show how to discover the index of each real character (honoring surrogates) in a string.
   Sub EnumTextElementIndexes(s As String)
      ' This StringBuilder holds the output results.
      Dim sb As New StringBuilder()

      ' Use the ParseCombiningCharacters method to 
      ' get the index of each real character in the string.
      Dim textElemIndex() As Integer = StringInfo.ParseCombiningCharacters(s)

      ' Iterate through each real character showing the character and the index where it was found.
      For i As Int32 = 0 To textElemIndex.Length - 1
         sb.AppendFormat("Character {0} starts at index {1}{2}",
                         i, textElemIndex(i), Environment.NewLine)
      Next

      ' Show the results.
      Console.WriteLine("Result of ParseCombiningCharacters:")
      Console.WriteLine(sb)
   End Sub
End Module
' The example displays the following output:
'
'       Result of GetTextElementEnumerator:
'       Character at index 0 is 'ā̈'
'       Character at index 3 is 'b'
'       Character at index 4 is 'ç'
'       
'       Result of ParseCombiningCharacters:
'       Character 0 starts at index 0
'       Character 1 starts at index 3
'       Character 2 starts at index 4

설명

.NET은 텍스트 요소를 단일 문자, 즉 그래프로 표시되는 텍스트 단위로 정의합니다. 텍스트 요소는 기본 문자, 서로게이트 쌍 또는 결합 문자 시퀀스일 수 있습니다. 유니코드 표준은 서로게이트 쌍을 두 개의 코드 단위 시퀀스로 구성된 단일 추상 문자에 대한 코딩된 문자 표현으로 정의합니다. 여기서 쌍의 첫 번째 단위는 상위 서로게이트이고 두 번째 단위는 낮은 서로게이트입니다. 유니코드 표준은 결합 문자 시퀀스를 기본 문자와 하나 이상의 결합 문자 조합으로 정의합니다. 서로게이트 쌍은 기본 문자 또는 결합 문자를 나타낼 수 있습니다.

StringInfo 클래스를 사용하면 문자열을 개별 Char 개체가 아닌 일련의 텍스트 요소로 사용할 수 있습니다.

지정된 문자열을 StringInfo 나타내는 개체를 인스턴스화하려면 다음 중 하나를 수행할 수 있습니다.

다음 두 가지 방법으로 문자열의 개별 텍스트 요소를 사용할 수 있습니다.

  • 각 텍스트 요소를 열거합니다. 이렇게 하려면 메서드를 호출한 다음 메서드가 GetTextElementEnumerator 를 반환false할 때까지 반환된 TextElementEnumerator 개체에서 메서드를 반복적으로 호출 MoveNext 합니다.

  • 메서드를 ParseCombiningCharacters 호출하여 각 텍스트 요소의 시작 인덱스가 포함된 배열을 검색합니다. 그런 다음, 이러한 인덱스를 메서드에 전달하여 개별 텍스트 요소를 검색할 SubstringByTextElements 수 있습니다.

다음 예제에서는 문자열의 텍스트 요소를 사용하는 두 가지 방법을 보여 줍니다. 두 개의 문자열을 만듭니다.

  • strCombining은 여러 Char 개체가 있는 세 개의 텍스트 요소를 포함하는 아랍어 문자 문자열입니다. 첫 번째 텍스트 요소는 기본 문자 ARABIC LETTER ALEF(U+0627)와 아래 아랍어 HAMZA(U+0655) 및 아랍어 KASRA(U+0650)입니다. 두 번째 텍스트 요소는 아랍어 LETTER HEH(U+0647)와 아랍어 FATHA(U+064E)입니다. 세 번째 텍스트 요소는 아랍어 LETTER BEH(U+0628)와 아랍어 DAMMATAN(U+064C)입니다.

  • strSurrogates은 3개의 서로게이트 쌍을 포함하는 문자열입니다. 보조 다국어 평면의 그리스어 ACROPHONIC FIVE TALENTS(U+10148), 보조 이디오그래픽 평면의 U+20026 및 개인 사용자 영역의 U+F1001. 각 문자의 UTF-16 인코딩은 높은 서로게이트와 낮은 서로게이트로 구성된 서로게이트 쌍입니다.

각 문자열은 메서드에 의해 ParseCombiningCharacters 한 번 구문 분석된 다음 메서드에 의해 구문 분석됩니다 GetTextElementEnumerator . 두 메서드 모두 두 문자열의 텍스트 요소를 올바르게 구문 분석하고 구문 분석 작업의 결과를 표시합니다.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      // The Unicode code points specify Arabic base characters and
      // combining character sequences.
      string strCombining = "\u0627\u0655\u0650\u064A\u0647\u064E" +
                            "\u0627\u0628\u064C";

      // The Unicode code points specify private surrogate pairs.
      string strSurrogates = Char.ConvertFromUtf32(0x10148) +
                             Char.ConvertFromUtf32(0x20026) + "a" +
                             Char.ConvertFromUtf32(0xF1001);

      EnumerateTextElements(strCombining);
      EnumerateTextElements(strSurrogates);
   }

   public static void EnumerateTextElements(string str)
   {
      // Get the Enumerator.
      TextElementEnumerator teEnum = null;

      // Parse the string using the ParseCombiningCharacters method.
      Console.WriteLine("\nParsing with ParseCombiningCharacters:");
      int[] teIndices = StringInfo.ParseCombiningCharacters(str);

      for (int i = 0; i < teIndices.Length; i++) {
         if (i < teIndices.Length - 1)
            Console.WriteLine("Text Element {0} ({1}..{2})= {3}", i,
               teIndices[i], teIndices[i + 1] - 1,
               ShowHexValues(str.Substring(teIndices[i], teIndices[i + 1] -
                             teIndices[i])));
         else
            Console.WriteLine("Text Element {0} ({1}..{2})= {3}", i,
               teIndices[i], str.Length - 1,
               ShowHexValues(str.Substring(teIndices[i])));
      }
      Console.WriteLine();

      // Parse the string with the GetTextElementEnumerator method.
      Console.WriteLine("Parsing with TextElementEnumerator:");
      teEnum = StringInfo.GetTextElementEnumerator(str);

      int teCount = - 1;

      while (teEnum.MoveNext()) {
         // Displays the current element.
         // Both GetTextElement() and Current retrieve the current
         // text element. The latter returns it as an Object.
         teCount++;
         Console.WriteLine("Text Element {0} ({1}..{2})= {3}", teCount,
            teEnum.ElementIndex, teEnum.ElementIndex +
            teEnum.GetTextElement().Length - 1, ShowHexValues((string)(teEnum.Current)));
      }
   }

   private static string ShowHexValues(string s)
   {
      string hexString = "";
      foreach (var ch in s)
         hexString += $"{(ushort)ch:X4} ";

      return hexString;
   }
}
// The example displays the following output:
//       Parsing with ParseCombiningCharacters:
//       Text Element 0 (0..2)= 0627 0655 0650
//       Text Element 1 (3..3)= 064A
//       Text Element 2 (4..5)= 0647 064E
//       Text Element 3 (6..6)= 0627
//       Text Element 4 (7..8)= 0628 064C
//
//       Parsing with TextElementEnumerator:
//       Text Element 0 (0..2)= 0627 0655 0650
//       Text Element 1 (3..3)= 064A
//       Text Element 2 (4..5)= 0647 064E
//       Text Element 3 (6..6)= 0627
//       Text Element 4 (7..8)= 0628 064C
//
//       Parsing with ParseCombiningCharacters:
//       Text Element 0 (0..1)= D800 DD48
//       Text Element 1 (2..3)= D840 DC26
//       Text Element 2 (4..4)= 0061
//       Text Element 3 (5..6)= DB84 DC01
//
//       Parsing with TextElementEnumerator:
//       Text Element 0 (0..1)= D800 DD48
//       Text Element 1 (2..3)= D840 DC26
//       Text Element 2 (4..4)= 0061
//       Text Element 3 (5..6)= DB84 DC01
Imports System.Globalization

Public Module Example
   Public Sub Main()
      ' The Unicode code points specify Arabic base characters and 
      ' combining character sequences.
      Dim strCombining As String = ChrW(&H627) & ChrW(&h0655) + ChrW(&H650) & 
              ChrW(&H64A) & ChrW(&H647) & ChrW(&H64E) & ChrW(&H627) & 
              ChrW(&H628) & ChrW(&H64C)

      ' The Unicode code points specify private surrogate pairs.
      Dim strSurrogates As String = Char.ConvertFromUtf32(&h10148) +
                                    Char.ConvertFromUtf32(&h20026) + "a" +
                                    Char.ConvertFromUtf32(&hF1001)
      
      EnumerateTextElements(strCombining)
      EnumerateTextElements(strSurrogates)
   End Sub

   Public Sub EnumerateTextElements(str As String)
      ' Get the Enumerator.
      Dim teEnum As TextElementEnumerator = Nothing      

      ' Parse the string using the ParseCombiningCharacters method.
      Console.WriteLine()
      Console.WriteLine("Parsing with ParseCombiningCharacters:")
      Dim teIndices As Integer() = StringInfo.ParseCombiningCharacters(str)
      
      For i As Integer = 0 To teIndices.Length - 1
         If i < teIndices.Length - 1 Then
            Console.WriteLine("Text Element {0} ({1}..{2})= {3}", i, 
               TEIndices(i), TEIndices((i + 1)) - 1, 
               ShowHexValues(str.Substring(TEIndices(i), TEIndices((i + 1)) - 
                             teIndices(i))))
         Else
            Console.WriteLine("Text Element {0} ({1}..{2})= {3}", i, 
               teIndices(i), str.Length - 1, 
               ShowHexValues(str.Substring(teIndices(i))))
         End If
      Next
      Console.WriteLine()

      ' Parse the string with the GetTextElementEnumerator method.
      Console.WriteLine("Parsing with TextElementEnumerator:")
      teEnum = StringInfo.GetTextElementEnumerator(str)

      Dim TECount As Integer = - 1

      While teEnum.MoveNext()
         ' Prints the current element.
         ' Both GetTextElement() and Current retrieve the current
         ' text element. The latter returns it as an Object.
         TECount += 1
         Console.WriteLine("Text Element {0} ({1}..{2})= {3}", teCount, 
            teEnum.ElementIndex, teEnum.ElementIndex + 
            teEnum.GetTextElement().Length - 1, ShowHexValues(CStr(teEnum.Current)))
      End While
   End Sub
   
   Private Function ShowHexValues(s As String) As String
      Dim hexString As String = ""
      For Each ch In s
         hexString += String.Format("{0:X4} ", Convert.ToUInt16(ch))
      Next
      Return hexString
   End Function
End Module
' The example displays the following output:
'       Parsing with ParseCombiningCharacters:
'       Text Element 0 (0..2)= 0627 0655 0650
'       Text Element 1 (3..3)= 064A
'       Text Element 2 (4..5)= 0647 064E
'       Text Element 3 (6..6)= 0627
'       Text Element 4 (7..8)= 0628 064C
'       
'       Parsing with TextElementEnumerator:
'       Text Element 0 (0..2)= 0627 0655 0650
'       Text Element 1 (3..3)= 064A
'       Text Element 2 (4..5)= 0647 064E
'       Text Element 3 (6..6)= 0627
'       Text Element 4 (7..8)= 0628 064C
'       
'       Parsing with ParseCombiningCharacters:
'       Text Element 0 (0..1)= D800 DD48
'       Text Element 1 (2..3)= D840 DC26
'       Text Element 2 (4..4)= 0061
'       Text Element 3 (5..6)= DB84 DC01
'       
'       Parsing with TextElementEnumerator:
'       Text Element 0 (0..1)= D800 DD48
'       Text Element 1 (2..3)= D840 DC26
'       Text Element 2 (4..4)= 0061
'       Text Element 3 (5..6)= DB84 DC01

호출자 참고

내부적으로 클래스의 StringInfo 메서드는 클래스의 메서드를 CharUnicodeInfo 호출하여 문자 범주를 결정합니다. .NET Framework 4.6.2부터 문자 분류는 유니코드 표준 버전 8.0.0을 기반으로 합니다. .NET Framework 4부터 .NET Framework 4.6.1까지의 경우 유니코드 표준 버전 6.3.0을 기반으로 합니다. .NET Core에서는 유니코드 표준 버전 8.0.0을 기반으로 합니다.

생성자

StringInfo()

StringInfo 클래스의 새 인스턴스를 초기화합니다.

StringInfo(String)

지정된 문자열로 StringInfo 클래스의 새 인스턴스를 초기화합니다.

속성

LengthInTextElements

현재 StringInfo 개체의 텍스트 요소 수를 가져옵니다.

String

현재 StringInfo 개체의 값을 가져오거나 설정합니다.

메서드

Equals(Object)

현재 StringInfo 개체가 지정된 개체와 같은지 여부를 나타냅니다.

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetHashCode()

현재 StringInfo 개체의 값에 대한 해시 코드를 계산합니다.

GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetNextTextElement(String)

지정된 문자열에 있는 첫째 텍스트 요소를 가져옵니다.

GetNextTextElement(String, Int32)

지정된 문자열의 지정된 인덱스에 있는 텍스트 요소를 가져옵니다.

GetNextTextElementLength(ReadOnlySpan<Char>)

입력 범위에서 발생하는 첫 번째 텍스트 요소(확장 그래프 클러스터)의 길이를 반환합니다.

GetNextTextElementLength(String)

입력 문자열에서 발생하는 첫 번째 텍스트 요소(확장 그래프 클러스터)의 길이를 반환합니다.

GetNextTextElementLength(String, Int32)

지정된 인덱스에서 시작하는 입력 문자열에서 발생하는 첫 번째 텍스트 요소(확장 그래프 클러스터)의 길이를 반환합니다.

GetTextElementEnumerator(String)

전체 문자열의 텍스트 요소를 반복하는 열거자를 반환합니다.

GetTextElementEnumerator(String, Int32)

지정된 인덱스에서 시작하여 문자열의 텍스트 요소를 반복하는 열거자를 반환합니다.

GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ParseCombiningCharacters(String)

지정된 문자열 내에 있는 각 기본 문자, 상위 서로게이트 또는 제어 문자를 반환합니다.

SubstringByTextElements(Int32)

현재 StringInfo 개체에서, 지정된 텍스트 요소에서 시작하여 마지막 텍스트 요소까지 계속되는 텍스트 요소의 부분 문자열을 검색합니다.

SubstringByTextElements(Int32, Int32)

현재 StringInfo 개체에서, 지정된 텍스트 요소에서 시작하여 지정된 수의 텍스트 요소까지 계속되는 텍스트 요소의 부분 문자열을 가져옵니다.

ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)

적용 대상

추가 정보