c - 为什么这个程序在使用大字符串时不能给出正确的结果?

标签 c string strchr

该程序接受字符串数量的输入,后跟实际字符串。输出应该是所有字符串的公共(public)字符数。

限制是:

  1. 字符串数量 <= 100
  2. 字符串长度 <= 100

例如..

输入:

3 ABC BCD CDE

输出:

1

因为只有 c 对所有字符串都是通用的。

当与小输入一起使用时,它可以提供正确的输出。

但是当与这样的大字符串一起使用时:https://hr-testcases.s3.amazonaws.com/2223/input19.txt?AWSAccessKeyId=AKIAINGOTNJCTGAUP7NA&Expires=1408959130&Signature=E%2BMnR6MA0gQNkuWHMvc70eCL5Dw%3D&response-content-type=text%2Fplain

它给出了错误的输出 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/

相关文章:

c - scanf 参数是否允许别名?

c++ - 如何修复堆错误?

c - 使用 MPI_BYTE 接收任何数据类型

javascript - 获取插入符所在的单词?

c - 如何在 C 中的字符串中找到字符的索引?

c - 逐字读取文件

c++ - 当我不使用标准字符串时,如何在 C++ 中将字符串转换为 int?

mysql - 如何将 URL 的整数子字符串内连接到整数?

c - 试图在一个字符之后复制字符串的其余部分

c - 查找第一次出现的未转义字符