我有這段代碼。當時並不明顯,但由於「fc」和「fcip」都以「fc」開頭,因此寫入的代碼總是會選擇第一個選項。String StartsWith()任何避免2次檢查的方法?
string fcportdelimit = "fc";
string fcipportdelimit = "fcip";
if (BlockToProcess[0].StartsWith(fcportdelimit))
{
try
{
this.ParseFCInterface(BlockToProcess);
}
catch (Exception E)
{
throw;
}
}
else if (BlockToProcess[0].StartsWith(fcipportdelimit))
{
try
{
this.ParseFCIPInterface(BlockToProcess);
}
catch (Exception E)
{
throw;
}
}
我查看了字符串類,但沒有看到將模式作爲輸入的StartsWith()或Contains()。我正在測試的字符串要麼是一個patttern fcN/N,要麼是fcipN,其中N是一個數字。所以,我想我必須做這樣的事情?
if (BlockToProcess[0].StartsWith(fcportdelimit || fcipportdelimit)
{
if (BlockToProcess[0].StartsWith(fcipportdelimit)
{
// do something here
}
else
{
//since fcipportdelimit didn't match it must be an fcport
//so do something else
}
}
'StartsWith(fcportdelimit || fcipportdelimit)'是有效的語法很遠...... – 2012-03-06 17:57:17
聽起來像是正是這類問題該正則表達式的是。也許看看他們。 – 2012-03-06 17:59:10
你考慮過正則表達式匹配嗎? – Brettski 2012-03-06 17:59:42