该程序接受字符串数量的输入,后跟实际字符串。输出应该是所有字符串的公共(public)字符数。
限制是:
- 字符串数量 <= 100
- 字符串长度 <= 100
例如..
输入:
3 ABC BCD CDE
输出:
1
因为只有 c 对所有字符串都是通用的。
当与小输入一起使用时,它可以提供正确的输出。
它给出了错误的输出 58 而不是 19。
这是我的代码:
#include<stdio.h>
#include<string.h>
void main(){
int n,i,j,count=0;
char s[100][100];
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%s",s[i]);
}
int t;
int l = strlen(s[0]);
for(i=0;i<l;i++){
t=0;
for(j=1;j<n;j++){
if(strchr(s[j],s[0][i])!='\0'){
t++;
}
}
if(t==n-1)
count++;
}
printf("%d",count);
}
最佳答案
当您迭代第一个字符串的字符时,您可能会多次找到相同的字符。
这意味着在第一个字符串中多次出现的常见字符将被计数多次。
这就是导致您的程序计算 58 而不是 19 的原因。
检查下面对您的程序的一些快速更新 - 它处理第一个字符串中的重复项。
该程序在 100 个字符串的测试用例上计算 19。
#include<stdio.h>
#include<string.h>
void main(){
int n,i,j/*,count=0*/;
int count[26] = {0}; /* counter per char */
char s[100][101];
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%s",s[i]);
}
int t;
int l = strlen(s[0]);
for(i=0;i<l;i++){
t=0;
/* convert char to integer - assuming lowercase char only */
int char_index = s[0][i] - 'a';
for(j=1;j<n;j++){
if(strchr(s[j],s[0][i])!='\0' && count[char_index] == 0){
t++;
}
}
if(t==n-1)
count[char_index] = 1;
/* count++; */
}
/* count how many chars are 1*/
int count_n = 0;
int index;
for (index = 0; index < 26; index ++)
{
if (count[index] == 1)
count_n ++;
}
printf("\n\n%d",count_n);
}
关于c - 为什么这个程序在使用大字符串时不能给出正确的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25481968/