Summary of several ways in C to split strings using split

  • 2020-05-09 19:09:30
  • OfStack

Method 1:


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 see that the result is a split of 1 specified character. Use another constructor to split multiple characters:


string s=abcdeabcdeabcde
string[] sArray1=s.Split(new char[3]{c,d,e}) ;
foreach(string i in sArray1)
Console.WriteLine(i.ToString());

The following results can be output:
ab
ab
ab

The third method:

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


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

The fourth method:


string str1= I ***** is *****1***** a ***** teach ***** t ;
string[] str2;
str1=str1.Replace(*****,*) ;
str2=str1.Split(*) ;
foreach(string i in str2)
Console.WriteLine(i.ToString()); 

Method 5:


string str1= I ** is *****1***** a ***** teach ***** t ;
 I want the result to be zero : I am a 1 A teacher. 
 If I take the number above 4 Doing so one way leads to the following mistake: I     is 1 A teacher. There is a space in the middle of the output, so the output result is not the desired result, which brings us back to the regular expression, in which case we can use the following number 5 Methods: 
string str1= I ** is *****1***** a ***** teach ***** t ;
string[] str2 = System.Text.RegularExpressions.Regex.Split(str1,@[*]+); 
foreach(string i in str2)
Console.WriteLine(i.ToString()); 

Here we accomplish our goal by [*]+ skillfully.


Related articles: