Summary of several methods to split strings using split in C #

Source: Internet
Author: User

Method 1:

Copy codeThe Code is as follows: string s = abcdeabcdeabcde;
String [] sArray = s. Split (c );
Foreach (string I in sArray)
Console. WriteLine (I. ToString ());

Output the following results:
AB
Deab
Deab
De

Method 2:

We can see that the result is separated by a specified character. Use another constructor to separate multiple characters:

Copy codeThe Code is as follows: string s = abcdeabcdeabcde
String [] sArray1 = s. Split (new char [3] {c, d, e });
Foreach (string I in sArray1)
Console. WriteLine (I. ToString ());

You can output the following results:
AB
AB
AB

Method 3:

In addition to the above two methods, the third method is to use a regular expression. Create a console project. Then add using System. Text. RegularExpressions;

Copy codeThe Code is as follows: System. Text. RegularExpressions
String content = agcsmallmacsmallgggsmallytx;
String [] resultString = Regex. Split (content, small, RegexOptions. IgnoreCase)
Foreach (string I in resultString)
Console. WriteLine (I. ToString ());

Output the following results:
Agc
Mac
Ggg
Ytx

Method 4:

Copy codeThe Code is as follows: string str1 = My *** is ********************** teacher;
String [] str2;
Str1 = str1.Replace (*****,*);
Str2 = str1.Split (*);
Foreach (string I in str2)
Console. WriteLine (I. ToString ());

Method 5:

Copy codeThe Code is as follows: string str1 = I'm;
The result I want to display is: I am a teacher.
If I use the fourth method above, the following error will occur: I am a teacher. There is a space in the middle of the output, so the output result is not the expected result, which returns to the regular expression, then you can use the fifth method below:
String str1 = I'm a ********************** teacher;
String [] str2 = System. Text. RegularExpressions. Regex. Split (str1, @ [*] + );
Foreach (string I in str2)
Console. WriteLine (I. ToString ());

Here, we use [*] + to skillfully accomplish our goal.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.