有限狀態機和上下文無關文法是相對應的,其在很多場合都很有用途。
寫了一個識別<p>***</p> 的有限狀態機的函數:
功能識別所有的開頭為<p>結尾為</p>,中間為任意字符的字符串。
private void openFileDelInitialFileAndSaveTargetFile(string filePath,int iCount)
...{
try
...{
int count = 0;
StringBuilder sbToWrite = new StringBuilder();
StreamReader sr = new StreamReader(filePath, System.Text.Encoding.Default);
for (int i = 0; i < 4; i++)
...{
sbToWrite.Append(sr.ReadLine());
sbToWrite.Append(" ");
count++;
}
string content = sr.ReadToEnd();
sr.Close();
==識別用的有限狀態機 ==#region ==識別用的有限狀態機 ==
Stack finateState = new Stack();
int iStart = 0;
int iStop = 0;
int z = 0;
foreach (char c in content)
...{
if (c == '<' && finateState.Count == 0)
...{
iStart = z;
finateState.Push(c);
z++;
continue;
}
if( (c == 'p'|| c=='P') && finateState.Count == 1)
...{
finateState.Push(c);
z++;
continue;
}
if (finateState.Count == 1)
...{
finateState.Pop();
z++;
continue;
}
if (c == '>' && finateState.Count == 2)
...{
finateState.Push(c);
z++;
continue;
}
if (finateState.Count == 2)
...{
finateState.Clear();
z++;
continue;
}
if (c == '<' && finateState.Count == 3)
...{
finateState.Push(c);
z++;
continue;
}
if (c == '/' && finateState.Count == 4)
...{
finateState.Push(c);
z++;
continue;
}
if (finateState.Count == 4)
...{
finateState.Pop();
z++;
continue;
}
if( (c == 'p'|| c=='P') && finateState.Count == 5)
...{
finateState.Push(c);
z++;
continue;
}
if (finateState.Count == 5)
...{
finateState.Pop();
finateState.Pop();
z++;
continue;
}
if (finateState.Count == 6 && c == '>')
...{
iStop = z;
string tmp = content.Substring(iStart, iStop - iStart+1).Trim();
iStart = 0;
iStop = 0;
sbToWrite.Append(tmp);
sbToWrite.Append(" ");
finateState.Clear();
count++;
z++;
continue;
}
if (finateState.Count == 6)
...{
finateState.Pop();
finateState.Pop();
finateState.Pop();
z++;
continue;
}
z++;
}
#endregion
File.Delete(filePath);
if (count > 4)
...{
int index = filePath.LastIndexOf('.');//dddd:dddf.txt
//filePath = filePath.Substring(0, index);
//filePath += ".txt";
index = filePath.LastIndexOf('\');
filePath = filePath.Substring(0, index);
filePath += "\"+iCount.ToString() + ".txt";
StreamWriter sw = new StreamWriter(filePath, false, Encoding.Default);
sw.Write(sbToWrite.ToString());
sw.Close();
}
}
catch (Exception e)
...{
Console.Write("Error:when try to weite the target file!");
Console.Write(e.Message);
}
}
}