C: evaluate part of the string
I cant find an expression to evaluate a part of a string.
开发者_开发知识库I want to get something like that:
if (string[4:8]=='abc') {...}
I started writing like this:
if (string[4]=='a' && string[5]=='b' && string[6]=='c') {...}
but if i need to evaluate a big part of string like
if (string[10:40] == another_string) {...}
then it gets to write TOO much expressions. Are there any ready-to-use solutions?
You could always use strncmp()
, so string[4:8] == "abc"
(which isn't C syntax, of course) could become strncmp(string + 4, "abc", 5) == 0
.
The standard C library function you want is strncmp
. strcmp
compares two C strings and -- as is the usual pattern, the "n" version deals with limited length data items.
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 */
The strncmp solutions others posted are probably the best. If you don't want to use strncmp, or simply want to know how to implement your own, you can write something like this:
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
精彩评论