views:

160

answers:

3

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?

+2  A: 

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 */
Brian
+6  A: 

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.

David Thornley
yeah, and to be totally correct the third argument of the function (5) should actually be 3 - equal to the length of the evaluated string.
Halst
You can use `sizeof "abc" - 1` there, which might make it a bit less error-prone than counting the characters by hand for very long strings.
caf
@Halst: Depends on the comparison. A [4:8] slice is not three characters long, no matter what the notation.
David Thornley
A: 

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
IVlad