簡體   English   中英

比較兩個數組元素的問題

[英]a problem in comparing two arrays' elements

As-salam Alaykom。 在這段代碼中,我試圖打印特定段落的每個字母字符的重復次數,如下所示:

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

通過使用stricmp function 在每個循環中比較兩個數組的元素。 但是它根本不打印任何東西和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);
    }

}

這里的問題是您比較的是characters而不是strings

在 C 中,字符串是 char arrays,末尾有一個 '\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);
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM