Let's say I have the following code and output:
for (j = 0; j <= i; j++)
printf("substring %d is %s\n", j,开发者_Python百科 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 get no output at all. What's wrong with my code?
You can't 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]);
}
}
You can't compare strings in C with == operator. You need to use strcmp function or strncmp.
Make certain you use strncmp and not strcmp. strcmp is profoundly unsafe.
BSD manpages (any nix will give you this info though):
man strncmp
int strncmp(const char *s1, const char *s2, size_t n);
The strcmp() and strncmp() functions lexicographically compare the null-terminated strings s1 and s2.
The strncmp() function compares not more than n characters. Because strncmp() is designed for comparing strings rather than binary data, characters that appear after a `\0' character are not compared.
The strcmp() and strncmp() return an integer greater than, equal to, or less than 0, according as the string s1 is greater than, equal to, or less than the string s2. The comparison is done using unsigned characters, so that \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;
}
You can use strncmp
:
if (!strncmp(sub_str[j], "max_n=20", 9)) {
Note the 9 is the length of the comparison string plus the final '\0'
. strncmp
is a little bit safer than strcmp
because you specify how many comparisons will be made at most.
精彩评论