split strncmp and combine?

split strncmp and combine?
typescript
Ethan Jackson

Say, instead of having a whole string "superman" I have a two split strings "super" and "man".

Suppose there is a pattern "batman", for the whole string "superman", strcmp( "superman", "batman" ) returns either a nagative or positive value depending on their lexicographical order, right?

Now I only have the split strings "super" and "man", and as I want to avoid strcat, can I somehow use separate strcmp with strncmp on the two split strings, respectively, and get the same return value as strcmp( "superman", "batman" )?

const char *prefix = "super"; const char *suffix = "man"; const char *pattern = "batman"; int len = strlen( pattern ) < strlen( prefix ) ? strlen( pattern ) : strlen( prefix ); int ret1 = strncmp( prefix, pattern, len ); int ret2 = // how? int ret = combine( ret1, ret2 ); // combine how?

The part I found extremely tricky is how return value of strcmp is defined, for what I searched, it seems to be dangerous to reply on specific return value of strcmp other than 0, negative, positive:(

Answer

You don't need combine(). You need smth like this

int len = strlen( prefix ); int ret1 = strncmp( prefix, pattern, len ); if (ret1 != 0) // If prefixes differ, then don't need to continue return ret1; // Compare suffixes return strcmp(pattern + len, suffix);

Note, you don't need the min length, strncmp ends at 0 character.

Related Articles