Method 1: Open vs.net to create a console project. Enter the following program in the Main () method.
String s = "abcdeabcdeabcde ";
String [] sArray = s. Split ('C ');
Foreach (string I in sArray)
Console. WriteLine (I. ToString ());
Output the following result: AB
Deab
Deab
De
We can see that the result is separated by a specified character. What if we want to use multiple characters for segmentation, such as c, d, and e? Well, we use another constructor:
Change
String s = "abcdeabcdeabcde
String [] sArray1 = s. Split (new char [3] {'C', 'D', 'E '});
Foreach (string I in sArray1)
Console. WriteLine (I. ToString ());
The following result can be output: AB
AB
AB
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;
Main (): change
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 result: agc mac ggg ytx
What are the advantages of using regular expressions? Don't worry, we will see its uniqueness later.
The following describes 4th methods. For example, string str1 = "My ***** is ********************** Teacher ";
If I want to show that I am a teacher, what should I do?
We can use the following code: string str1 = "My ***** is ************************ Teacher ";
String [] str2; str1 = str1.Replace ("*****", "*"); str2 = str1.Split ('*'); foreach (string I in str2) Console. writeLine (I. toString (); in this way, you can get the correct result. However, for example, string str1 = "I'm a ******************** Teacher ";
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 with space output, so the output is not what I want. How can I solve this problem? This returns to the regular expression (here we can see its power), then we 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 cleverly accomplish our goal. Ch (string I in str2) Console. WriteLine (I. ToString ());
Here, we use "[*]" to cleverly accomplish our goal.