Why does my string comparison fail?

Let's say I have the following code and output:

for (j = 0; j <= i; j++) printf("substring %d is %s\n", j, sub_str[j]); 

Output:

  substring 0 is max_n = 20
 substring 1 is max_m = 20 

Now I only want to print some substrings. However, if I try to do this conditionally:

 for (j=0; j <=i; j++) { if (sub_str[j] == "max_n=20") { printf("substring %d is %s\n", j, sub_str[j]); } } 

I do not get any output. What is wrong with my code?

+2
source share
4 answers

You cannot use == to compare strings in C. You must use strcmp .

 for (j=0; j<=i; j++) { if (strcmp(sub_str[j], "max_n=20") == 0) { printf("substring %d is %s\n", j, sub_str[j]); } } 
+6
source

You cannot compare strings in a C statement with ==. You need to use strcmp or strncmp .

+5
source

Make sure you use strncmp and not strcmp. strcmp is deeply insecure .

BSD manpages (any nix will give you this information):

 man strncmp int strncmp(const char *s1, const char *s2, size_t n); 

The strcmp () and strncmp () functions compare lexicographically strings s1 and s2 with zero completion.

The strncmp () function compares no more than n characters. Since strncmp () is intended to compare strings, not binary data, the characters that appear after the `\ 0 'character are not compared.

strcmp () and strncmp () return an integer greater than, equal to, or less than 0, in accordance with the fact that the string s1 is greater than, equal to, or less than the string s2. Comparison is performed using unsigned characters, so \200' is greater than \ 0'.

From: http://www.codecogs.com/reference/c/string.h/strcmp.php?alias=strncmp

 #include <stdio.h> #include <string.h> int main() { // define two strings s, t and initialize s char s[10] = "testing", t[10]; // copy s to t strcpy(t, s); // test if s is identical to t if (!strcmp(s, t)) printf("The strings are identical.\n"); else printf("The strings are different.\n"); return 0; } 
+3
source

You can use strncmp :

 if (!strncmp(sub_str[j], "max_n=20", 9)) { 

Note that 9 is the length of the comparison string plus the final '\0' . strncmp little safer than strcmp because you specify how many comparisons will be made maximum.

+2
source

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


All Articles