[英]c check two strings for same characters
我剛剛開始學習C編程,為了鍛煉,我發現了一項任務。 首先,我必須掃描兩個字符串。 然后,我必須逐個字符地比較它們,如果有任何相同的字符,我必須打印出相同字符的數量。 它必須使用指針來完成。 所以讓我有“ boat”和“ ship”,這樣程序將返回0。但是如果它是“ boat”和“ soap”,它將返回2。
這是到目前為止我所能獲得的,但是當我運行它時會給我錯誤。 我把錯誤放在注釋中。
在此先感謝您的幫助。
#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;
}
主要是您在程序中有很多多余的*
。 變量聲明應為:
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()
是一個危險的函數,可能導致緩沖區溢出。 剛開始時可以使用它,但是不要讓它成為一種習慣,也不要在生產代碼中使用它!
您錯誤地定義了字符數組,並且錯誤地使用了運算符*。
嘗試以下
#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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.