Split separator strings are commonly used. I just showed this on the internet and found that it is not bad. I haven't updated my blog for a long time. I have borrowed it for sending and sending. Maybe I can forget it later.
I have recently seen many posts in the forum asking me how to use them.SplitTo split the string.SplitMake some simple summary and hope to help you. The following describes several methods:
Method 1: OpenVs.netCreate a console project. ThenMain ()Enter the followingProgram.
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
We can see that the result is separated by a specified character. If we want to use multiple characters for segmentation, as shown in figureC, D, EWhat should we do? Well, we use another constructor.:
ChangeString 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
In addition to the above two methods,The third method is to use a regular expression. Create a console project. Then addUsing system. Text. regularexpressions;
Main ():To
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
UseWhat are the advantages of 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 followingCode:
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 will returnRegular Expression (here we can see its power)In this case, the fifth method can be used:
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.