Because C # 's split is more restrictive, you can only use characters or character arrays to make delimiters. does not provide the same as VB can be used as a string split function, so in the process of writing a program, a lot less convenience.
So, write the following function to facilitate their own programming.
The procedure is as follows:
=====================================================
using System;
using System.Collections;
namespace Split
... {
class Mysplit
... {
[STAThread]
static void Main (string[] args)
... {
string Str1= "", str2= "";
if (args. Length!= 2)
... {
Console.WriteLine ("Please enter a string to split:");
str1 = Console.ReadLine ();
Console.WriteLine ("Please enter a separator:");
str2 = Console.ReadLine ();
Console.WriteLine ("Segmented data is as follows:");
}
Else
... {
str1 = args[0];
str2 = args[1];
}
string[] output = null;
Output = Split (STR1,STR2);
for (int i=0 i < output. Length; i++)
... {
Console.WriteLine ("{0}", Output[i]);
}
Console.WriteLine ("Split into {0} strings!"), output. Length);
TimeSpan sp1,sp2,sp3;
DateTime dt = DateTime.Now;
for (int i=0; i<1000; i++)
... {
Output=split (STR1,STR2);
Output=null;
}
Sp1=datetime.now-dt;
//split with && character!
System.Text.RegularExpressions.Regex RG = new System.Text.RegularExpressions.Regex ("&{2}");
dt = DateTime.Now;
for (int j=0; j<1000; j + +)
... {
Output=rg. Split (STR1);
Output=null;
}
Sp2=datetime.now-dt;
Console.WriteLine ("Regular class execution time: {0}", SP2.) ToString ());
Console.WriteLine ("Homemade function Execution time: {0}", SP1.) ToString ());
Console.WriteLine ("Input carriage return exit program!");
Console.read ();
}
//Split function start
public static string[] Split (string strinput, String sp)
... {
string tmp= "";
int strlen=0, splen=0;
int found=0;
string[] rt = NULL;
Try
... {
if (strinput==null | | sp==null | | strinput. length==0 | | Sp. LENGTH==0) return null;
//Initializes a list of arrays (as a dynamic array)
ArrayList Tmp3 = new ArrayList ();
strlen = strinput. Length;
Splen = sp. Length;
for (int i=0 i
... {
//Lookup separator
found = strinput. IndexOf (sp, i);
if (found>=0)
... {
tmp = "";
//character string before
tmp = strinput. Substring (i, found-i);
//Add to Array list
Tmp3. ADD (TMP);
i = found+splen-1;
}
Else
... {
string tmp2= "";
//Take the last string
TMP2 = strinput. Substring (i);
if (tmp2!= "")
Tmp3. ADD (TMP2);
break;
}
}
//sets the dimensions of the dynamic array to the actual number of elements, because the array list is incremented by the number of dimensions in multiples of 16
Tmp3. TrimToSize ();
The
//convert array list is an array of strings and returns.
RT = (string[]) Tmp3. ToArray (typeof (String));
Tmp3. Clear ();
}
catch (Exception e)
... {
//console.writeline ("{0}", e.message);
throw E;
}
return RT;
}
}
}
After testing, this function is one-fold faster than the regular-style split!