프로그래밍/C#

[C#] C# string.Substring 메서드

불타는홍당무 2019. 9. 26. 17:48

public string Substring (int startIndex);

 

인스턴스에서 startIndex부터 마지막까지의 부분 문자열을 검색한다. 현재의 인스턴스 값은 수정되지 않는다. *인덱스는 0부터 시작한다.

using System;

public class Example
{
   public static void Main()
   {
      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));
      }                          
   }
}

[결과]

Key: Color1, Value: 'red'

Key: Color2, Value: 'green'

Key: Color3, Value: 'blue'

Key: Title, Value: 'Code Repository

 

 

public string Substring (int startIndex, int length);

 

인스턴스에서 startIndex부터 length길이의 부분 문자열을 검색한다. 현재의 인스턴스 값은 수정되지 않는다.

using System;

public class Example
{
   public static void Main()
   {
      String value = "This is a string.";
      int startIndex = 5;
      int length = 2;
      String substring = value.Substring(startIndex, length);

      Console.WriteLine(substring);
   }
}

[결과]

is