将字符串 strcmp() 函数与字符串的 2d 指针进行比较?
compare string strcmp() function with 2d pointer of string?
我正在练习下面的代码
int main() {
int N, Q, cnt;
scanf("%d", &N);
char **str1=(char**)malloc(sizeof(char*)*N);
for(int i=0; i<N; i++) {
str1[i]=(char*)malloc(sizeof(char)*20);
scanf("%[^\n]s", str1[i]);
}
scanf("%d", &Q);
char **str2=(char**)malloc(sizeof(char*)*Q);
for(int i=0; i<Q; i++) {
str2[i]=(char*)malloc(sizeof(char)*20);
scanf("%[^\n]s", str2[i]);
}
for(int i=0; i<Q; i++) {
for(int j=0, cnt=0; j<N; j++) {
// if statement
if( strcmp(str2[i], str1[j]) == 0) cnt++;
}
printf("%d\n", cnt);
}
for(int i=0; i<N; i++){
free(str1[i]);
}
for(int i=0; i<Q; i++) {
free(str2[i]);
}
free(str1);
free(str2);
return 0;
}
STD 输入是
4
aaa
bbb
ccc
aaa
3
aaa
bbb
cca
比打印出来
2
1
0
因为
- 'aaa'是2倍
- 'bbb'是1倍
- 'cca'是0次
if( strcmp(str2[i], str1[j]) == 0) cnt++;
但是 if 语句不算 cnt++
怎么了,我的 strcmp() 代码?
您有两个名为 cnt
的变量。
在这一行声明了一个:
int N, Q, cnt;
并限定为整个函数。
在这一行声明了一个:
for(int j=0, cnt=0; j<N; j++) {
并限定在 for
循环中。
语句 cnt++
修改第二个语句,因为它在 for 循环内。
语句 printf("%d\n", cnt);
打印第一个,因为它在 for 循环之外。
我正在练习下面的代码
int main() {
int N, Q, cnt;
scanf("%d", &N);
char **str1=(char**)malloc(sizeof(char*)*N);
for(int i=0; i<N; i++) {
str1[i]=(char*)malloc(sizeof(char)*20);
scanf("%[^\n]s", str1[i]);
}
scanf("%d", &Q);
char **str2=(char**)malloc(sizeof(char*)*Q);
for(int i=0; i<Q; i++) {
str2[i]=(char*)malloc(sizeof(char)*20);
scanf("%[^\n]s", str2[i]);
}
for(int i=0; i<Q; i++) {
for(int j=0, cnt=0; j<N; j++) {
// if statement
if( strcmp(str2[i], str1[j]) == 0) cnt++;
}
printf("%d\n", cnt);
}
for(int i=0; i<N; i++){
free(str1[i]);
}
for(int i=0; i<Q; i++) {
free(str2[i]);
}
free(str1);
free(str2);
return 0;
}
STD 输入是
4
aaa
bbb
ccc
aaa
3
aaa
bbb
cca
比打印出来
2
1
0
因为
- 'aaa'是2倍
- 'bbb'是1倍
- 'cca'是0次
if( strcmp(str2[i], str1[j]) == 0) cnt++;
但是 if 语句不算 cnt++
怎么了,我的 strcmp() 代码?
您有两个名为 cnt
的变量。
在这一行声明了一个:
int N, Q, cnt;
并限定为整个函数。
在这一行声明了一个:
for(int j=0, cnt=0; j<N; j++) {
并限定在 for
循环中。
语句 cnt++
修改第二个语句,因为它在 for 循环内。
语句 printf("%d\n", cnt);
打印第一个,因为它在 for 循环之外。