首页 > 解决方案 > 比较两个数组元素的问题

问题描述

阿萨拉姆·阿莱科姆。在这段代码中,我试图打印特定段落的每个字母字符的重复次数,如下所示:

a ----> "Number of recurrences"
b ----> "Number of recurrences"
and so on...

通过使用stricmp函数在每个循环中比较两个数组的元素。但它根本不打印任何内容和 0 个错误,这是什么问题?!?!?!?!?

#inlcude <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
#include <string.h>
#include <time.h>

void main()
{
    int i, j;
    int z = 0;
    char h, g;
    char y[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    char x[620] = {"C is a general purpose computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone laboratories for use with the unix operating system... and more which is not visible in the image."}; 
    for(j = 0; j < 26; j++)
    {
        for(i = 0; i < 609; i++)
        {
            if(stricmp(y[j], x[i]) == 0)
            {
                z++;
            }
        }
        printf("y[j] -------> %d", z);
    }

}

标签: arrayscstring

解决方案


这里的问题是您正在比较charactersno strings

在 C 中,字符串是 char 数组,末尾带有 '\0'。

例如:

这是一个 C 字符:'C'

这是一个 C 字符串:'C\0'

stricmp期待两个字符串,而您正在传递两个字符。

因此,要实现解决方案,您需要比较字符和您的程序正在运行。

if(toupper(y[j]) == toupper(x[i]))

#include <stdlib.h>
#include <conio.h>
#include <math.h>
#include <string.h>
#include <time.h>

void main()
{
    int i, j;
    int z = 0;
    char h, g;
    char y[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    char x[620] = {"C is a general purpose computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone laboratories for use with the unix operating system... and more which is not visible in the image."}; 
    for(j = 0; j < 26; j++)
    {
        for(i = 0; i < 609; i++)
        {

            if(toupper(y[j]) == toupper(x[i]))
            {
                z++;
            }
        }
        printf("y[j] -------> %d \n", z);
    }

}

推荐阅读