c检查两个字符串为相同的字符
我刚开始学习C编程和练习,我发现一个任务。首先,我必须扫描两个字符串。然后,我必须逐字比较它们,如果有任何相同的字符,我必须打印出相同字符的数量。 它必须用指针来完成。因此,让我有“船”和“船”,所以程序将返回0.但如果它是“船”和“肥皂”它将返回2.c检查两个字符串为相同的字符
这是我迄今为止,但当我运行它会给我错误。我把错误置于评论中。
在此先感谢您的帮助。
#include <stdio.h>
#include <string.h>
int number_of_same_characters(char *, char *);
int main()
{
char * first[100];
char * second[100];
int result = 0;
printf("Enter first string\n");
gets(*first);
printf("Enter second string\n");
gets(*second);
result = number_of_same_characters(*first, *second);
printf("%d\n", result);
return 0;
}
int number_of_same_characters(char *p, char *q){ //i get this error here - error: invalid type argument of unary ‘*’ (have ‘int’)
int counter = 0;
for(int j = 0; *p[j] != '\0' || *q[j] != '\0'; ++j){ //i get this error here - error: invalid type argument of unary ‘*’ (have ‘int’)
if(strcmp(*p[j], *q[j])){
++counter;
}
}
return counter;
}
您错误地定义了字符数组,并且错误地使用了运算符*。
尝试使用以下
#include <stdio.h>
#include <string.h>
#define N 100
int number_of_same_characters(const char *, const char *);
int main()
{
char first[N];
char second[N];
int result = 0;
size_t n;
printf("Enter first string: ");
fgets(first, N, stdin);
n = strlen(first);
if (first[n - 1] == '\n') first[n - 1] = '\0';
printf("Enter second string: ");
fgets(second, N, stdin);
n = strlen(second);
if (second[n - 1] == '\n') second[n - 1] = '\0';
result = number_of_same_characters(first, second);
printf("%d\n", result);
return 0;
}
int number_of_same_characters(const char *p, const char *q)
{
int counter = 0;
int i;
for(i = 0; p[i] != '\0' && q[i] != '\0'; ++i)
{
if (p[i] == q[i]) ++counter;
}
return counter;
}
如果进入船和肥皂那么输出将是
2
非常感谢!它的工作原理。 – niko85 2014-09-28 17:26:06
@ niko85我有一个错字。应该有(i = 0; p [i]!='\ 0'&& q [i]!='\ 0'; ++ i) – 2014-09-28 17:44:32
主要是你已经得到了很多的额外*
的乱扔垃圾的计划。变量的声明应该是:
char first[100];
char second[100];
输入调用应该是†:
gets(first);
gets(second);
方法调用应该是:
result = number_of_same_characters(first, second);
最后不应该有任何for循环中的解引用。
for(int j = 0; p[j] != '\0' || q[j] != '\0'; ++j){
if(strcmp(p[j], q[j])){
++counter;
}
}
这会让你更接近,虽然仍然有一些问题。作为提示,||
运营商是可疑的,你不需要使用strcmp
。
†值得指出的是gets()
是一个危险的函数,可能会导致缓冲区溢出。当你刚刚起步时可以使用它,但不要让它成为一种习惯,并且永远不要在生产代码中使用它!
'字符*第一个[100];' - >'炭第一[100]; ' - >'获取(第一)' - >'number_of_same_characters(第一,第二)' - > ...等 – BLUEPIXY 2014-09-28 15:46:26
['gets' is evil](https://www.gnu.org/software/的libc /手动/ html_node /线路Input.html#指数得到)。不要使用它。 – 5gon12eder 2014-09-28 15:49:14