C: evaluate part of the string

I cannot find an expression to evaluate part of a string.

I want to get something like this:

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 most of the string for example

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

then he gets a lot of words. Are there any ready-to-use solutions?

+4
source share
3 answers

You can always use strncmp() , so string[4:8] == "abc" (which is not C syntax, of course) can become strncmp(string + 4, "abc", 5) == 0 .

+6
source

The standard C library function you want is strncmp . strcmp compares two C strings and, like a regular pattern, version "n" deals with data elements of limited length.

 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 */ 
+2
source

strncmp other publications are probably the best. If you don't want to use strncmp or just 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 
0
source

Source: https://habr.com/ru/post/1306288/


All Articles