2010-04-07 120 views
4

我找不到表達式來評估字符串的一部分。C:評估字符串的一部分

我想類似的東西:

if (string[4:8]=='abc') {...} 

我開始寫這樣的:

if (string[4]=='a' && string[5]=='b' && string[6]=='c') {...} 

,但如果我需要評估字符串的重要組成部分像

if (string[10:40] == another_string) {...} 

然後它寫太多的表達式。有沒有現成的解決方案?

回答

6

你總是可以使用strncmp(),所以string[4:8] == "abc"(這不是C語法,當然)可能成爲strncmp(string + 4, "abc", 5) == 0

+1

是的,並完全正確的函數的第三個參數(5)實際上應該是3 - 等於評估字符串的長度。 – Halst 2010-04-07 22:12:47

+1

你可以在那裏使用'sizeof「abc」 - 1「,這可能會使得它比用於非常長的字符串的手動計算字符更容易出錯。 – caf 2010-04-07 22:15:45

+0

@Halst:取決於比較。一個[4:8]片不是三個字符長,不管記號如何。 – 2010-04-08 13:24:17

2

你想要的標準C庫函數是strncmpstrcmp比較兩個C字符串和 - 如通常的模式,「n」版本處理有限的長度數據項。

if(0==strncmp(string1+4, "abc", 4)) 
    /* this bit will execute if string1 
     ends with "abc" (incluing the implied null) 
     after the first four chars */ 
0

strncmp其他人發佈的解決方案可能是最好的。如果你不想使用strncmp,或者只是想知道如何實現你自己,你可以寫這樣的東西:

int ok = 1; 
for (int i = start; i <= stop; ++i) 
    if (string[i] != searchedStr[i - start]) 
    { 
     ok = 0; 
     break; 
    } 

if (ok) { } // found it 
else  { } // didn't find it