当前位置: 首页>>代码示例>>C#>>正文


C# String.Split方法代码示例

本文整理汇总了C#中System.String.Split方法的典型用法代码示例。如果您正苦于以下问题:C# String.Split方法的具体用法?C# String.Split怎么用?C# String.Split使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.String的用法示例。


在下文中一共展示了String.Split方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: foreach

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 (System.Text.RegularExpressions.Match m in 
      System.Text.RegularExpressions.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;
         }
      }
开发者ID:.NET开发者,项目名称:System,代码行数:25,代码来源:String.Split

输出:

16 + 21 = 37
31 * 3 = 93
28 / 3 = 9.33
42 - 18 = 24
12 * 7 = 84

示例2:

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 (System.Text.RegularExpressions.Match m in 
   System.Text.RegularExpressions.Regex.Matches(input, pattern))
   Console.WriteLine("{0}: {1}", ++ctr, m.Groups[1].Value);
开发者ID:.NET开发者,项目名称:System,代码行数:9,代码来源:String.Split

输出:

1: This is captured
text.
2: This is more captured text.
3: Some more captured text:
Option1
Option2
4: Terse text.

示例3:

String input = "abacus -- alabaster - * - atrium -+- " +
               "any -*- actual - + - armoire - - alarm";
String pattern = @"\s-\s?[+*]?\s?-\s";
String[] elements = System.Text.RegularExpressions.Regex.Split(input, pattern);
foreach (var element in elements)
   Console.WriteLine(element);
开发者ID:.NET开发者,项目名称:System,代码行数:6,代码来源:String.Split

输出:

abacus
alabaster
atrium
any
actual
armoire
alarm

示例4: if

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);
开发者ID:.NET开发者,项目名称:System,代码行数:22,代码来源:String.Split

输出:

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.

示例5: Show

// This example demonstrates the String() methods that use
// the StringSplitOptions enumeration.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
            "ONE[stop][stop]" +
            "TWO[stop][stop][stop]" +
            "THREE[stop][stop]";
char[] charSeparators = new char[] {','};
string[] stringSeparators = new string[] {"[stop]"};
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");

// Display the original string and delimiter characters.
Console.WriteLine("1a )The original string is \"{0}\".", s1);
Console.WriteLine("The delimiter character is '{0}'.\n", 
                   charSeparators[0]);

// Split a string delimited by characters and return all elements.
Console.WriteLine("1b) Split a string delimited by characters and " +
                  "return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);

// Split a string delimited by characters and return all non-empty elements.
Console.WriteLine("1c) Split a string delimited by characters and " +
                  "return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the original string into the string and empty string before the 
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("1d) Split a string delimited by characters and " +
                  "return 2 elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the original string into the string after the delimiter and the 
// remainder of the original string after the delimiter.
Console.WriteLine("1e) Split a string delimited by characters and " +
                  "return 2 non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
Console.WriteLine("2) Split a string delimited by another string:\n");

// Display the original string and delimiter string.
Console.WriteLine("2a) The original string is \"{0}\".", s2);
Console.WriteLine("The delimiter string is \"{0}\".\n", stringSeparators[0]);

// Split a string delimited by another string and return all elements.
Console.WriteLine("2b) Split a string delimited by another string and " +
                  "return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);

// Split the original string at the delimiter and return all non-empty elements.
Console.WriteLine("2c) Split a string delimited by another string and " +
                  "return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the original string into the empty string before the 
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("2d) Split a string delimited by another string and " +
                  "return 2 elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the original string into the string after the delimiter and the 
// remainder of the original string after the delimiter.
Console.WriteLine("2e) Split a string delimited by another string and " + 
                  "return 2 non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Display the array of separated strings using a local function
void Show(string[] entries)
{
    Console.WriteLine("The return value contains these {0} elements:", entries.Length);
    foreach (string entry in entries)
    {
        Console.Write("<{0}>", entry);
    }
    Console.Write("\n\n");
}
开发者ID:.NET开发者,项目名称:System,代码行数:91,代码来源:String.Split

输出:

1) Split a string delimited by characters:

1a )The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.

1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><><><><><>

1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:


1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<>

1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:


2) Split a string delimited by another string:

2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".

2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><><><><><>

2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:


2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<>

2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:

示例6:

string phrase = "The quick  brown fox";
string[] words;

words = phrase.Split(default(Char[]), 3, StringSplitOptions.RemoveEmptyEntries);

words = phrase.Split((char[]) null, 3, StringSplitOptions.RemoveEmptyEntries);

words = phrase.Split(null as char[], 3, StringSplitOptions.RemoveEmptyEntries);
开发者ID:.NET开发者,项目名称:System,代码行数:8,代码来源:String.Split

示例7:

string phrase = "The quick  brown fox";
string[] words;

words = phrase.Split(default(string[]), 3, StringSplitOptions.RemoveEmptyEntries);

words = phrase.Split((string[]) null, 3, StringSplitOptions.RemoveEmptyEntries);

words = phrase.Split(null as string[], 3, StringSplitOptions.RemoveEmptyEntries);
开发者ID:.NET开发者,项目名称:System,代码行数:8,代码来源:String.Split

示例8: elements

string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]";
   string[] stringSeparators = new string[] {"[stop]"};
   string[] result;
   
   // Display the original string and delimiter string.
   Console.WriteLine("Splitting the string:\n   \"{0}\".", source);
   Console.WriteLine();
   Console.WriteLine("Using the delimiter string:\n   \"{0}\"", 
                     stringSeparators[0]);
   Console.WriteLine();                           
      
   // Split a string delimited by another string and return all elements.
   result = source.Split(stringSeparators, StringSplitOptions.None);
   Console.WriteLine("Result including all elements ({0} elements):", 
                     result.Length);
   Console.Write("   ");
   foreach (string s in result)
   {
      Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);                   
   }
   Console.WriteLine();
   Console.WriteLine();

   // Split delimited by another string and return all non-empty elements.
   result = source.Split(stringSeparators, 
                         StringSplitOptions.RemoveEmptyEntries);
   Console.WriteLine("Result including non-empty elements ({0} elements):", 
                     result.Length);
   Console.Write("   ");
   foreach (string s in result)
   {
      Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);                   
   }
   Console.WriteLine();

   // The example displays the following output:
   //    Splitting the string:
   //       "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
   //    
   //    Using the delimiter string:
   //       "[stop]"
   //    
   //    Result including all elements (9 elements):
   //       '<>' 'ONE' '<>' 'TWO' '<>' '<>' 'THREE' '<>' '<>'
   //    
   //    Result including non-empty elements (3 elements):
   //       'ONE' 'TWO' 'THREE'
开发者ID:.NET开发者,项目名称:System,代码行数:47,代码来源:String.Split

示例9:

string[] separators = {",", ".", "!", "?", ";", ":", " "};
string value = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate.";
string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (var word in words)
   Console.WriteLine(word);
开发者ID:.NET开发者,项目名称:System,代码行数:5,代码来源:String.Split

输出:

The
handsome
energetic
young
dog
was
playing
with
his
smaller
more
lethargic
litter
mate

示例10:

string phrase = "The quick  brown fox";
string[] words;

words = phrase.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);

words = phrase.Split((string[]) null, StringSplitOptions.RemoveEmptyEntries);

words = phrase.Split(null as string[], StringSplitOptions.RemoveEmptyEntries);
开发者ID:.NET开发者,项目名称:System,代码行数:8,代码来源:String.Split

示例11:

string phrase = "The quick  brown fox";
string[] words;

words = phrase.Split(default(Char[]), StringSplitOptions.RemoveEmptyEntries);

words = phrase.Split((char[]) null, StringSplitOptions.RemoveEmptyEntries);

words = phrase.Split(null as char[], StringSplitOptions.RemoveEmptyEntries);
开发者ID:.NET开发者,项目名称:System,代码行数:8,代码来源:String.Split

示例12: for

string delimStr = " ,.:";
char [] delimiter = delimStr.ToCharArray();
string words = "one two,three:four.";
string [] split = null;

Console.WriteLine("The delimiters are -{0}-", delimStr);
for (int x = 1; x <= 5; x++) 
{
   split = words.Split(delimiter, x);
   Console.WriteLine("\ncount = {0,2} ..............", x);
   foreach (var s in split) 
   {
       Console.WriteLine("-{0}-", s);
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:15,代码来源:String.Split

输出:

The delimiters are - ,.:-
count =  1 ..............
-one two,three:four.-
count =  2 ..............
-one-
-two,three:four.-
count =  3 ..............
-one-
-two-
-three:four.-
count =  4 ..............
-one-
-two-
-three-
-four.-
count =  5 ..............
-one-
-two-
-three-
-four-
--

示例13: if

string words = "This is a list of words, with: a bit of punctuation" +
               "\tand a tab character.";

string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' });

foreach (string s in split) 
{

    if (s.Trim() != "")
        Console.WriteLine(s);
}
开发者ID:.NET开发者,项目名称:System,代码行数:11,代码来源:String.Split

输出:

This
is
a
list
of
words
with
a
bit
of
punctuation
and
a
tab
character

示例14:

String value = "This is a short string.";
Char delimiter = 's';
String[] substrings = value.Split(delimiter);
foreach (var substring in substrings)
   Console.WriteLine(substring);
开发者ID:.NET开发者,项目名称:System,代码行数:5,代码来源:String.Split

输出:

Thi
i
a
hort
tring.

示例15: String.Split(String splittor)

//引入命名空间
using System;

class MainClass
{

  public static void Main()
  {
    string[] myStrings = {"To", "be", "or", "not", "to", "be"};
    string myString9 = String.Join(".", myStrings);    
    myStrings = myString9.Split('.');
    foreach (string mySplitString in myStrings)
    {
      Console.WriteLine("mySplitString = " + mySplitString);
    }
  }

}
开发者ID:C#程序员,项目名称:System,代码行数:18,代码来源:String.Split


注:本文中的System.String.Split方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。