用正則表達式實現識別單詞:
using System.Text.RegularExpressions;
//解析
private void button1_Click(object sender, System.EventArgs e)
{
//字符串不能爲空
if(t_scr.Text=="")
{
MessageBox.Show("請輸入一串字符!");
return;
}
TimeSpan t1=new TimeSpan(DateTime.Now.Ticks);
Regex myr=new Regex(@"\W+");
string soruce=t_scr.Text;
string[] danci=myr.Split(soruce);
int strLen=danci.Length;
string[] realStr=new string[strLen];
int j=0,current=0;
bool flag=false; //不存在
for(int i=0;i<strLen;i++)
{
j=0;
flag=false;
while(j<=current)
{
if(realStr[j]!=danci[i])
j++;
else
{
flag=true;
break;
}
}
if(flag)
continue;
realStr[current]=danci[i];
current++;
}
int realLen=current;
t_res.Text=string.Empty;
for(int i=0;i<realLen;i++)
{
current=0;
for(j=0;j<strLen;j++)
{
if(realStr[i]==danci[j])
current++;
}
t_res.AppendText(realStr[i]+" 出現次數:"+current+"\r\n");
}
TimeSpan t2=new TimeSpan(DateTime.Now.Ticks);
TimeSpan ts=t2.Subtract(t1).Duration();
msg.Text="原始字符串長度:"+strLen+"\r\n"+
"出現的非重複單詞數:"+realLen+"\r\n"+
"運行時間:"+ts.Minutes+"分"+ts.Seconds+"秒"+ts.Milliseconds+"毫秒";
}
注:本篇爲單詞分析器源碼,用到了正則表達式優化算法
其中t_scr,msg,t_res爲三個TextBox,t_scr存放輸入的源字符串,msg爲統計結果,t_res爲輸出的單詞
-----------------------------------------------------------------