Recently, someone asked me how to use split. To split the string. Split I hope it will be helpful to 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.: Change 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
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 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 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 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 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. |