Recently I have seen many posts in the forum asking how to use split to split strings. Here I will make some simple summary of split, hoping to help you. The following describes several methods:
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 to 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.
There are spaces in the middle of the output, so the output result is not what I want. How can this problem be solved? 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 ());