String.Substring 메서드

정의

이 인스턴스에서 부분 문자열을 검색합니다.

이 멤버는 오버로드됩니다. 구문, 사용법 및 예제를 비롯하여 이 멤버에 대한 자세한 내용을 보려면 오버로드 목록에서 이름을 클릭합니다.

오버로드

Substring(Int32)

이 인스턴스에서 부분 문자열을 검색합니다. 부분 문자열은 지정된 문자 위치에서 시작하고 문자열 끝까지 계속됩니다.

Substring(Int32, Int32)

이 인스턴스에서 부분 문자열을 검색합니다. 부분 문자열은 지정된 문자 위치에서 시작하고 길이도 지정되어 있습니다.

Substring(Int32)

이 인스턴스에서 부분 문자열을 검색합니다. 부분 문자열은 지정된 문자 위치에서 시작하고 문자열 끝까지 계속됩니다.

public:
 System::String ^ Substring(int startIndex);
public string Substring (int startIndex);
member this.Substring : int -> string
Public Function Substring (startIndex As Integer) As String

매개 변수

startIndex
Int32

이 인스턴스의 substring에 있는 0부터 시작하는 문자 위치입니다.

반환

이 인스턴스의 startIndex에서 시작하는 부분 문자열에 해당하는 문자열이거나, Empty가 이 인스턴스의 길이와 같으면 startIndex입니다.

예외

startIndex가 0보다 작거나 이 인스턴스 길이보다 큽니다.

예제

다음 예제에서는 문자열에서 부분 문자열을 가져오는 방법을 보여 줍니다.

using namespace System;
using namespace System::Collections;

int main()
{
   array<String^>^info = { "Name: Felica Walker", "Title: Mz.",
                           "Age: 47", "Location: Paris", "Gender: F"};
   int found = 0;
   Console::WriteLine("The initial values in the array are:");
   for each (String^ s in info) 
      Console::WriteLine(s);

   Console::WriteLine("\nWe want to retrieve only the key information. That is:");
   for each (String^ s in info) { 
      found = s->IndexOf(": ");
      Console::WriteLine("   {0}", s->Substring(found + 2));
   }
}
// The example displays the following output:
//       The initial values in the array are:
//       Name: Felica Walker
//       Title: Mz.
//       Age: 47
//       Location: Paris
//       Gender: F
//       
//       We want to retrieve only the key information. That is:
//       Felica Walker
//       Mz.
//       47
//       Paris
//       F
string [] info = { "Name: Felica Walker", "Title: Mz.", 
                   "Age: 47", "Location: Paris", "Gender: F"};
int found = 0;

Console.WriteLine("The initial values in the array are:");
foreach (string s in info)
    Console.WriteLine(s);

Console.WriteLine("\nWe want to retrieve only the key information. That is:");        
foreach (string s in info) 
{
    found = s.IndexOf(": ");
    Console.WriteLine("   {0}", s.Substring(found + 2));
}

// The example displays the following output:
//       The initial values in the array are:
//       Name: Felica Walker
//       Title: Mz.
//       Age: 47
//       Location: Paris
//       Gender: F
//       
//       We want to retrieve only the key information. That is:
//          Felica Walker
//          Mz.
//          47
//          Paris
//          F
let info = 
    [| "Name: Felica Walker"; "Title: Mz."
       "Age: 47"; "Location: Paris"; "Gender: F" |]

printfn "The initial values in the array are:"
for s in info do
    printfn $"{s}"

printfn "\nWe want to retrieve only the key information. That is:"
for s in info do
    let found = s.IndexOf ": "
    printfn $"   {s.Substring(found + 2)}"

// The example displays the following output:
//       The initial values in the array are:
//       Name: Felica Walker
//       Title: Mz.
//       Age: 47
//       Location: Paris
//       Gender: F
//
//       We want to retrieve only the key information. That is:
//          Felica Walker
//          Mz.
//          47
//          Paris
//          F
Public Class SubStringTest
    Public Shared Sub Main()
        Dim info As String() = { "Name: Felica Walker", "Title: Mz.", 
                                 "Age: 47", "Location: Paris", "Gender: F"}
        Dim found As Integer = 0
       
        Console.WriteLine("The initial values in the array are:")
        For Each s As String In info
            Console.WriteLine(s)
        Next s

        Console.WriteLine(vbCrLf + "We want to retrieve only the key information. That is:")
        For Each s As String In info
            found = s.IndexOf(": ")
            Console.WriteLine("   {0}", s.Substring(found + 2))
        Next s
    End Sub 
End Class 
' The example displays the following output:
'       The initial values in the array are:
'       Name: Felica Walker
'       Title: Mz.
'       Age: 47
'       Location: Paris
'       Gender: F
'       
'       We want to retrieve only the key information. That is:
'          Felica Walker
'          Mz.
'          47
'          Paris
'          F

다음 예제에서는 메서드를 Substring 사용하여 등호(=) 문자로 구분된 키/값 쌍을 구분합니다.

String[] pairs = { "Color1=red", "Color2=green", "Color3=blue",
                 "Title=Code Repository" };
foreach (var pair in pairs) 
{
    int position = pair.IndexOf("=");
    if (position < 0)
        continue;
    Console.WriteLine("Key: {0}, Value: '{1}'", 
                   pair.Substring(0, position),
                   pair.Substring(position + 1));
}                          

// The example displays the following output:
//     Key: Color1, Value: 'red'
//     Key: Color2, Value: 'green'
//     Key: Color3, Value: 'blue'
//     Key: Title, Value: 'Code Repository'
let pairs = 
    [| "Color1=red"; "Color2=green"; "Color3=blue"
       "Title=Code Repository" |]
for pair in pairs do
    let position = pair.IndexOf "="
    if position >= 0 then
        printfn $"Key: {pair.Substring(0, position)}, Value: '{pair.Substring(position + 1)}'"

// The example displays the following output:
//     Key: Color1, Value: 'red'
//     Key: Color2, Value: 'green'
//     Key: Color3, Value: 'blue'
//     Key: Title, Value: 'Code Repository'
Module Example
   Public Sub Main()
      Dim pairs() As String = { "Color1=red", "Color2=green", "Color3=blue",
                                "Title=Code Repository" }
      For Each pair In pairs
         Dim position As Integer = pair.IndexOf("=")
         If position < 0 then Continue For
         Console.WriteLine("Key: {0}, Value: '{1}'", 
                           pair.Substring(0, position),
                           pair.Substring(position + 1))
      Next                          
   End Sub
End Module
' The example displays the following output:
'     Key: Color1, Value: 'red'
'     Key: Color2, Value: 'green'
'     Key: Color3, Value: 'blue'
'     Key: Title, Value: 'Code Repository'

메서드는 IndexOf 문자열에서 등가 문자의 위치를 가져오는 데 사용됩니다. 메서드에 Substring(Int32, Int32) 대한 호출은 문자열의 첫 번째 문자에서 시작하여 메서드 호출에서 반환 IndexOf 된 문자 수에 대해 확장되는 키 이름을 추출합니다. 그런 다음 메서드를 Substring(Int32) 호출하면 키에 할당된 값이 추출됩니다. 같음 문자를 넘어 한 문자 위치에서 시작하여 문자열의 끝까지 확장됩니다.

설명

메서드를 Substring(Int32) 호출하여 지정된 문자 위치에서 시작하여 문자열의 끝에서 끝나는 문자열에서 부분 문자열을 추출합니다. 시작 문자 위치는 0부터 시작합니다. 즉, 문자열의 첫 번째 문자는 인덱스 1이 아니라 인덱스 0에 있습니다. 지정된 문자 위치에서 시작하여 문자열의 끝 전에 끝나는 부분 문자열을 추출하려면 메서드를 호출합니다 Substring(Int32, Int32) .

참고

이 메서드는 현재 instance 값을 수정하지 않습니다. 대신 현재 문자열의 위치에서 시작하는 새 문자열을 반환합니다 startIndex .

특정 문자 또는 문자 시퀀스로 시작하는 부분 문자열을 추출하려면 또는 IndexOf 와 같은 IndexOf 메서드를 호출하여 값을 startIndex가져옵니다. 두 번째 예제에서는 이를 보여 줍니다. 문자 뒤에 = 하나의 문자 위치를 시작하는 키 값을 추출합니다.

가 0과 같으면 startIndex 메서드는 변경되지 않은 원래 문자열을 반환합니다.

추가 정보

적용 대상

Substring(Int32, Int32)

이 인스턴스에서 부분 문자열을 검색합니다. 부분 문자열은 지정된 문자 위치에서 시작하고 길이도 지정되어 있습니다.

public:
 System::String ^ Substring(int startIndex, int length);
public string Substring (int startIndex, int length);
member this.Substring : int * int -> string
Public Function Substring (startIndex As Integer, length As Integer) As String

매개 변수

startIndex
Int32

이 인스턴스의 substring에 있는 0부터 시작하는 문자 위치입니다.

length
Int32

부분 문자열에 있는 문자의 수입니다.

반환

이 인스턴스의 length에서 시작하는 startIndex 길이의 부분 문자열에 해당하는 문자열이거나, Empty가 이 인스턴스의 길이와 같고 startIndex가 0이면 length입니다.

예외

startIndex + length는 문자 위치가 이 인스턴스 안에 없음을 나타냅니다.

또는

startIndex 또는 length가 0보다 작습니다.

예제

다음 예제에서는 여섯 번째 문자 위치(즉, 인덱스 5)에서 시작하는 문자열에서 두 문자를 추출하는 메서드에 대한 간단한 호출 Substring(Int32, Int32) 을 보여 줍니다.

String value = "This is a string.";
int startIndex = 5;
int length = 2;
String substring = value.Substring(startIndex, length);
Console.WriteLine(substring);

// The example displays the following output:
//       is
let value = "This is a string."
let startIndex = 5
let length = 2
let substring = value.Substring(startIndex, length)
printfn $"{substring}"

// The example displays the following output:
//       is
Module Example
   Public Sub Main()
      Dim value As String = "This is a string."
      Dim startIndex As Integer = 5
      Dim length As Integer = 2
      Dim substring As String = value.Substring(startIndex, length)
      Console.WriteLine(substring)
   End Sub
End Module
' The example displays the following output:
'       is

다음 예제에서는 다음 세 가지 경우의 메서드를 사용하여 Substring(Int32, Int32) 문자열 내에서 부분 문자열을 격리합니다. 두 경우에서 부분 문자열은 비교에 사용되며, 세 번째 경우 잘못된 매개 변수가 지정되어 예외가 throw됩니다.

  • 문자열의 세 번째 위치(인덱스 2)에서 단일 문자를 추출하고 "c"와 비교합니다. 이 비교는 를 반환합니다 true.

  • 문자열의 네 번째 위치(인덱스 3)에서 시작하여 0자를 추출하여 메서드에 IsNullOrEmpty 전달합니다. 메서드에 대한 호출이 를 반환하기 때문에 true를 Substring 반환합니다 String.Empty.

  • 문자열의 네 번째 위치에서 시작하는 한 문자를 추출하려고 시도합니다. 해당 위치에 문자가 없으므로 메서드 호출은 예외를 ArgumentOutOfRangeException throw합니다.

string myString = "abc";
bool test1 = myString.Substring(2, 1).Equals("c"); // This is true.
Console.WriteLine(test1);
bool test2 = string.IsNullOrEmpty(myString.Substring(3, 0)); // This is true.
Console.WriteLine(test2);
try
{
   string str3 = myString.Substring(3, 1); // This throws ArgumentOutOfRangeException.
   Console.WriteLine(str3);
}
catch (ArgumentOutOfRangeException e)
{
   Console.WriteLine(e.Message);
}

// The example displays the following output:
//       True
//       True
//       Index and length must refer to a location within the string.
//       Parameter name: length
let myString = "abc"
let test1 = myString.Substring(2, 1).Equals "c" // This is true.
printfn $"{test1}"
let test2 = String.IsNullOrEmpty(myString.Substring(3, 0)) // This is true.
printfn $"{test2}"
try
    let str3 = myString.Substring(3, 1) // This throws ArgumentOutOfRangeException.
    printfn $"{str3}"
with :? ArgumentOutOfRangeException as e ->
    printfn $"{e.Message}"

// The example displays the following output:
//       True
//       True
//       Index and length must refer to a location within the string.
//       Parameter name: length
Public Class Sample
   Public Shared Sub Main()
      Dim myString As String = "abc"
      Dim test1 As Boolean = myString.Substring(2, 1).Equals("c") ' This is true.
      Console.WriteLine(test1)
      Dim test2 As Boolean = String.IsNullOrEmpty(myString.Substring(3, 0)) ' This is true.
      Console.WriteLine(test2)
      Try  
         Dim str3 As String = myString.Substring(3, 1) ' This throws ArgumentOutOfRangeException.
         Console.WriteLine(str3)
      Catch e As ArgumentOutOfRangeException
         Console.WriteLIne(e.Message)
      End Try   
   End Sub
End Class 
' The example displays the following output:
'       True
'       True
'       Index and length must refer to a location within the string.
'       Parameter name: length

다음 예제에서는 메서드를 Substring 사용하여 등호(=) 문자로 구분된 키/값 쌍을 구분합니다.

String[] pairs = { "Color1=red", "Color2=green", "Color3=blue",
                 "Title=Code Repository" };
foreach (var pair in pairs) 
{
    int position = pair.IndexOf("=");
    if (position < 0)
        continue;
    Console.WriteLine("Key: {0}, Value: '{1}'", 
                   pair.Substring(0, position),
                   pair.Substring(position + 1));
}                          

// The example displays the following output:
//     Key: Color1, Value: 'red'
//     Key: Color2, Value: 'green'
//     Key: Color3, Value: 'blue'
//     Key: Title, Value: 'Code Repository'
let pairs = 
    [| "Color1=red"; "Color2=green"; "Color3=blue"
       "Title=Code Repository" |]
for pair in pairs do
    let position = pair.IndexOf "="
    if position >= 0 then
        printfn $"Key: {pair.Substring(0, position)}, Value: '{pair.Substring(position + 1)}'"

// The example displays the following output:
//     Key: Color1, Value: 'red'
//     Key: Color2, Value: 'green'
//     Key: Color3, Value: 'blue'
//     Key: Title, Value: 'Code Repository'
Module Example
   Public Sub Main()
      Dim pairs() As String = { "Color1=red", "Color2=green", "Color3=blue",
                                "Title=Code Repository" }
      For Each pair In pairs
         Dim position As Integer = pair.IndexOf("=")
         If position < 0 then Continue For
         Console.WriteLine("Key: {0}, Value: '{1}'", 
                           pair.Substring(0, position),
                           pair.Substring(position + 1))
      Next                          
   End Sub
End Module
' The example displays the following output:
'     Key: Color1, Value: 'red'
'     Key: Color2, Value: 'green'
'     Key: Color3, Value: 'blue'
'     Key: Title, Value: 'Code Repository'

메서드는 IndexOf 문자열에서 등가 문자의 위치를 가져오는 데 사용됩니다. 메서드에 Substring(Int32, Int32) 대한 호출은 문자열의 첫 번째 문자에서 시작하여 메서드 호출에서 반환 IndexOf 된 문자 수에 대해 확장되는 키 이름을 추출합니다. 그런 다음 메서드를 Substring(Int32) 호출하면 키에 할당된 값이 추출됩니다. 같음 문자를 넘어 한 문자 위치에서 시작하여 문자열의 끝까지 확장됩니다.

설명

메서드를 Substring(Int32, Int32) 호출하여 지정된 문자 위치에서 시작하여 문자열의 끝 전에 끝나는 문자열에서 부분 문자열을 추출합니다. 시작 문자 위치는 0부터 시작합니다. 즉, 문자열의 첫 번째 문자는 인덱스 1이 아니라 인덱스 0에 있습니다. 지정된 문자 위치에서 시작하여 문자열의 끝까지 계속되는 부분 문자열을 추출하려면 메서드를 호출합니다 Substring(Int32) .

참고

이 메서드는 현재 instance 값을 수정하지 않습니다. 대신 현재 문자열의 위치에서 시작하는 문자가 lengthstartIndex 있는 새 문자열을 반환합니다.

매개 변수는 length 현재 문자열 instance 추출할 총 문자 수를 나타냅니다. 여기에는 인덱 startIndex스 에 있는 시작 문자가 포함됩니다. 즉, 메서드는 Substring 인덱스에서 인덱 + startIndexstartIndexlength 스로 문자를 추출하려고 시도합니다( 1).

특정 문자 또는 문자 시퀀스로 시작하는 부분 문자열을 추출하려면 또는 LastIndexOf 와 같은 IndexOf 메서드를 호출하여 값을 startIndex가져옵니다.

부분 문자열이 에서 startIndex 지정된 문자 시퀀스로 확장되어야 하는 경우 또는 LastIndexOf 와 같은 IndexOf 메서드를 호출하여 끝 문자 또는 문자 시퀀스의 인덱스를 가져올 수 있습니다. 그런 다음, 다음과 같이 해당 값을 문자열의 인덱스 위치로 변환할 수 있습니다.

  • 부분 문자열 length 의 끝을 표시하는 단일 문자를 검색한 경우 매개 변수는 + 1과 같endIndexstartIndex - 으며 여기서 endIndex 은 또는 LastIndexOf 메서드의 IndexOf 반환 값입니다. 다음 예제에서는 문자열에서 "b" 문자의 연속 블록을 추출합니다.

    String s = "aaaaabbbcccccccdd";
    Char charRange = 'b';
    int startIndex = s.IndexOf(charRange);
    int endIndex = s.LastIndexOf(charRange);
    int length = endIndex - startIndex + 1;
    Console.WriteLine("{0}.Substring({1}, {2}) = {3}",
                    s, startIndex, length, 
                    s.Substring(startIndex, length));
    
    // The example displays the following output:
    //       aaaaabbbcccccccdd.Substring(5, 3) = bbb
    
    let s = "aaaaabbbcccccccdd"
    let charRange = 'b'
    let startIndex = s.IndexOf charRange
    let endIndex = s.LastIndexOf charRange
    let length = endIndex - startIndex + 1
    printfn $"{s}.Substring({startIndex}, {length}) = {s.Substring(startIndex, length)}"
    
    // The example displays the following output:
    //       aaaaabbbcccccccdd.Substring(5, 3) = bbb
    
    Module Example
       Public Sub Main()
          Dim s As String = "aaaaabbbcccccccdd"
          Dim charRange As Char = "b"c
          Dim startIndex As Integer = s.Indexof(charRange)
          Dim endIndex As Integer = s.LastIndexOf(charRange)
          Dim length = endIndex - startIndex + 1
          Console.WriteLine("{0}.Substring({1}, {2}) = {3}",
                            s, startIndex, length, 
                            s.Substring(startIndex, length))
       End Sub
    End Module
    ' The example displays the following output:
    '     aaaaabbbcccccccdd.Substring(5, 3) = bbb
    
  • 부분 문자열의 끝을 표시할 여러 문자를 검색한 경우 매개 변수는 와 같 - + startIndexendMatchLengthendIndex고, length 여기서 endIndex 는 또는 LastIndexOf 메서드의 IndexOf 반환 값이고 endMatchLength 는 부분 문자열의 끝을 표시하는 문자 시퀀스의 길이입니다. 다음 예제에서는 XML <definition> 요소가 포함된 텍스트 블록을 추출합니다.

    String s = "<term>extant<definition>still in existence</definition></term>";
    String searchString = "<definition>";
    int startIndex = s.IndexOf(searchString);
    searchString = "</" + searchString.Substring(1);
    int endIndex = s.IndexOf(searchString);
    String substring = s.Substring(startIndex, endIndex + searchString.Length - startIndex);
    Console.WriteLine("Original string: {0}", s);
    Console.WriteLine("Substring;       {0}", substring); 
    
    // The example displays the following output:
    //     Original string: <term>extant<definition>still in existence</definition></term>
    //     Substring;       <definition>still in existence</definition>
    
    let s = "<term>extant<definition>still in existence</definition></term>"
    let searchString = "<definition>"
    let startIndex = s.IndexOf(searchString)
    let searchString = "</" + searchString.Substring 1
    let endIndex = s.IndexOf searchString
    let substring = s.Substring(startIndex, endIndex + searchString.Length - startIndex)
    printfn $"Original string: {s}"
    printfn $"Substring;       {substring}"
    
    // The example displays the following output:
    //     Original string: <term>extant<definition>still in existence</definition></term>
    //     Substring;       <definition>still in existence</definition>
    
    Module Example
       Public Sub Main()
          Dim s As String = "<term>extant<definition>still in existence</definition></term>"
          Dim searchString As String = "<definition>"
          Dim startindex As Integer = s.IndexOf(searchString)
          searchString = "</" + searchString.Substring(1)
          Dim endIndex As Integer = s.IndexOf(searchString)
          Dim substring As String = s.Substring(startIndex, endIndex + searchString.Length - StartIndex)
          Console.WriteLine("Original string: {0}", s)
          Console.WriteLine("Substring;       {0}", substring) 
       End Sub
    End Module
    ' The example displays the following output:
    '   Original string: <term>extant<definition>still in existence</definition></term>
    '   Substring;       <definition>still in existence</definition>
    
  • 문자 또는 문자 시퀀스가 부분 문자열 length 의 끝에 포함되지 않은 경우 매개 변수는 와 같으며endIndexstartIndex - , 여기서 endIndex 은 또는 LastIndexOf 메서드의 IndexOf 반환 값입니다.

가 0과 같고 현재 문자열의 길이와 length 같으면 startIndex 메서드는 원래 문자열을 변경하지 않고 반환합니다.

추가 정보

적용 대상