被解析我需要解析一條線,是在一個類似的格式如下:區分字符串中使用字符串分割
s = "Jun 21 09:47:50 ez-x5 user.debug if_comm: [TX] 02 30 20 0f 30 31 39 24 64 31 30 31 03 54 ";
我分割線與[TX]或[RX]。這就是我做的解析字符串:
s = "Jun 21 09:47:50 ez-x5 user.debug if_comm: [TX] 02 30 20 0f 30 31 39 24 64 31 30 31 03 54 ";
string[] stringSeparators = new string[] { "[TX] " + start_key };
string transfer = s.Split(stringSeparators, 2, StringSplitOptions.None)[1];
//At this point, transfer[] = 02 30 20 0f 30 31 39 24 64 31 30 31 03 54
if (!string.IsNullOrEmpty(transfer))
{
string key = "";
string[] split = transfer.Split(' ');
if (split[0] == start_key)
{
for (int i = 0; i < key_length; i++)
{
key += split[i + Convert.ToInt32(key_index)];
}
TX_Handle(key);
}
}
stringSeparators = new string[] { "[RX]" + start_key };
transfer = s.Split(stringSeparators, 2, StringSplitOptions.None)[1];
if (!string.IsNullOrEmpty(transfer))
{
string key = "";
string[] split = transfer.Split(' ');
if (split[0] == start_key)
{
for (int i = 0; i < key_length; i++)
{
key += split[i + Convert.ToInt32(key_index)];
}
RX_Handle(key);
}
}
基本上,因爲我有比較給定的令牌是否[TX]或[RX]沒有現實的途徑,我被迫使用上述方法來分離字符串,這要求我寫兩次基本相同的代碼。
什麼是我可以解決這個問題的方法,並知道哪個令牌被解析,以便我不必重複我的代碼?
你的答案是如此之快和親是StackOverflow的拒絕我接受它作爲另一個3分鐘回答 – l46kok 2012-07-21 04:28:54