이 문서는 기계 번역을 이용하여 번역되었습니다. 문서를 영문으로 보려면 영문 확인란을 선택하세요. 마우스 포인터를 텍스트 위로 이동시켜 팝업 창에서 영문 텍스트를 표시할 수도 있습니다.
번역
영문

String.Split 메서드

 

게시 날짜: 2016년 11월

지정된 문자열 또는 유니코드 문자 배열의 요소로 구분된 이 인스턴스의 부분 문자열이 포함된 문자열 배열을 반환합니다.

네임스페이스:   System
어셈블리:  mscorlib(mscorlib.dll에 있음)

이름설명
System_CAPS_pubmethodSplit(Char[])

문자열을 배열 내 문자에 기초하는 하위 문자열로 분할합니다.

System_CAPS_pubmethodSplit(Char[], Int32)

배열에 있는 문자에 따라 최대 개수의 부분 문자열로 문자열을 분할합니다. 반환할 부분 문자열의 최대 수도 지정합니다.

System_CAPS_pubmethodSplit(Char[], Int32, StringSplitOptions)

배열에 있는 문자에 따라 최대 개수의 부분 문자열로 문자열을 분할합니다.

System_CAPS_pubmethodSplit(Char[], StringSplitOptions)

배열에 있는 문자에 따라 문자열을 부분 문자열로 분할합니다. 부분 문자열이 빈 배열 요소를 포함하는지 여부를 지정할 수 있습니다.

System_CAPS_pubmethodSplit(String[], Int32, StringSplitOptions)

배열에 있는 문자열에 따라 최대 개수의 부분 문자열로 문자열을 분할합니다. 부분 문자열이 빈 배열 요소를 포함하는지 여부를 지정할 수 있습니다.

System_CAPS_pubmethodSplit(String[], StringSplitOptions)

배열에 있는 문자열에 따라 문자열을 부분 문자열로 분할합니다. 부분 문자열이 빈 배열 요소를 포함하는지 여부를 지정할 수 있습니다.

Split is used to break a delimited string into substrings. You can use either a character array to specify zero, one, or multiple delimiting characters (the Split(Char[]) method), or you can use a character array to specify zero, one, or multiple delimiting strings. Overloads of the Split method allow you to limit the number of substrings returned by the method (the Split(Char[], Int32) method), to determine whether empty strings are included in the returned substrings (the Split(Char[], StringSplitOptions) and Split(String[], StringSplitOptions) methods, or to do both (the Split(Char[], Int32, StringSplitOptions) and Split(String[], Int32, StringSplitOptions) methods).

System_CAPS_important중요

For more detailed information on the Overload:System.String.Split method, as well as for examples that call each overload, see the documentation for the individual overloads of Overload:System.String.Split.

The M:System.String.Split(System.Char[]) method is not always the best way to break a delimited string into substrings. If you don't want to extract all of the substrings of a delimited string, or if you want to parse a string based on a pattern instead of a set of delimiter characters, consider the following alternatives.

If your strings conform to a fixed pattern, you can use a regular expression to extract and handle their elements. For example, if strings take the form "numberoperandnumber" you can use a regular expression to extract and handle the string's elements. Here's an example:

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      String[] expressions = { "16 + 21", "31 * 3", "28 / 3",
                               "42 - 18", "12 * 7",
                               "2, 4, 6, 8" };
      String pattern = @"(\d+)\s+([-+*/])\s+(\d+)";
      foreach (var expression in expressions)
         foreach (Match m in Regex.Matches(expression, pattern)) {
            int value1 = Int32.Parse(m.Groups[1].Value);
            int value2 = Int32.Parse(m.Groups[3].Value);
            switch (m.Groups[2].Value)
            {
               case "+":
                  Console.WriteLine("{0} = {1}", m.Value, value1 + value2);
                  break;
               case "-":
                  Console.WriteLine("{0} = {1}", m.Value, value1 - value2);
                  break;
               case "*":
                  Console.WriteLine("{0} = {1}", m.Value, value1 * value2);
                  break;
               case "/":
                  Console.WriteLine("{0} = {1:N2}", m.Value, value1 / value2);
                  break;
            }
         }
   }
}
// The example displays the following output:
//       16 + 21 = 37
//       31 * 3 = 93
//       28 / 3 = 9.33
//       42 - 18 = 24
//       12 * 7 = 84

The regular expression pattern (\d+)\s+([-+*/])\s+(\d+) is defined like this:

Pattern

Description

(\d+)

Match one or more decimal digits. This is the first capturing group.

\s+

Match one or more whitespace characters.

([-+*/])

Match an arithmetic operator sign (+, -, *, or /). This is the second capturing group.

\s+

Match one or more whitespace characters.

(\d+)

Match one or more decimal digits. This is the third capturing group.

You can also use a regular expression to extract substrings from a string based on a pattern rather than a fixed set of characters. This is a common scenario when either of these conditions occurs:

  • One or more of the delimiter characters does not always serve as a delimiter in the T:System.String instance.

  • The sequence and number of delimiter characters is variable or unknown.

For example, the M:System.String.Split(System.Char[]) method cannot be used to split the following string, because the number of \n (in C#) or vbCrLf (in Visual Basic) characters is variable, and they do not always serve as delimiters.


[This is captured\ntext.]\n\n[\n[This is more captured text.]\n]
\n[Some more captured text:\n   Option1\n   Option2][Terse text.] 

A regular expression can split this string easily, as the following example shows.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      String input = "[This is captured\ntext.]\n\n[\n" +
                     "[This is more captured text.]\n]\n" +
                     "[Some more captured text:\n   Option1" +
                     "\n   Option2][Terse text.]";
      String pattern = @"\[([^\[\]]+)\]";
      int ctr = 0;
      foreach (Match m in Regex.Matches(input, pattern))
         Console.WriteLine("{0}: {1}", ++ctr, m.Groups[1].Value);
   }
}
// The example displays the following output:
//       1: This is captured
//       text.
//       2: This is more captured text.
//       3: Some more captured text:
//          Option1
//          Option2
//       4: Terse text.

The regular expression pattern \[([^\[\]]+)\] is defined like this:

Pattern

Description

\[

Match an opening bracket.

([^\[\]]+)

Match any character that is not an opening or a closing bracket one or more times. This is the first capturing group.

\]

Match a closing bracket.

The M:System.Text.RegularExpressions.Regex.Split(System.String) method is almost identical to M:System.String.Split(System.Char[]), except that it splits a string based on a regular expression pattern instead of a fixed character set. For example, the following example uses the M:System.Text.RegularExpressions.Regex.Split(System.String) method to split a string that contains substrings delimited by various combinations of hyphens and other characters.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      String input = "abacus -- alabaster - * - atrium -+- " +
                     "any -*- actual - + - armoir - - alarm";
      String pattern = @"\s-\s?[+*]?\s?-\s";
      String[] elements = Regex.Split(input, pattern);
      foreach (var element in elements)
         Console.WriteLine(element);
   }
}
// The example displays the following output:
//       abacus
//       alabaster
//       atrium
//       any
//       actual
//       armoir
//       alarm

The regular expression pattern \s-\s?[+*]?\s?-\s is defined like this:

Pattern

Description

\s-

Match a whitespace character followed by a hyphen.

\s?

Match zero or one whitespace character.

[+*]?

Match zero or one occurrence of either the + or * character.

\s?

Match zero or one whitespace character.

-\s

Match a hyphen followed by a whitespace character.

If you aren't interested in all of the substrings in a string, you might prefer to work with one of the string comparison methods that returns the index at which the match begins. You can then call the M:System.String.Substring(System.Int32) method to extract the substring that you want. The string comparison methods include:

  • IndexOf, which returns the zero-based index of the first occurrence of a character or string in a string instance.

  • IndexOfAny, which returns the zero-based index in the current string instance of the first occurrence of any character in a character array.

  • LastIndexOf, which returns the zero-based index of the last occurrence of a character or string in a string instance.

  • LastIndexOfAny, which returns a zero-based index in the current string instance of the last occurrence of any character in a character array.

The following example uses the M:System.String.IndexOf(System.Char) method to find the periods in a string. It then uses the M:System.String.Substring(System.Int32) method to return full sentences.

using System;
using System.Collections.Generic;

public class Example
{
   public static void Main()
   {
      String value = "This is the first sentence in a string. " +
                     "More sentences will follow. For example, " +
                     "this is the third sentence. This is the " +
                     "fourth. And this is the fifth and final " +
                     "sentence.";
      var sentences = new List<String>();
      int position = 0;
      int start = 0;
      // Extract sentences from the string.
      do {
         position = value.IndexOf('.', start);
         if (position >= 0) {
            sentences.Add(value.Substring(start, position - start + 1).Trim());
            start = position + 1;
         }
      } while (position > 0);

      // Display the sentences.
      foreach (var sentence in sentences)
         Console.WriteLine(sentence);
   }
}
// The example displays the following output:
//       This is the first sentence in a string.
//       More sentences will follow.
//       For example, this is the third sentence.
//       This is the fourth.
//       And this is the fifth and final sentence.
맨 위로 이동
표시: