2010-04-07 93 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