arrays - 比较两个数组元素的问题
问题描述
阿萨拉姆·阿莱科姆。在这段代码中,我试图打印特定段落的每个字母字符的重复次数,如下所示:
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);
}
}
解决方案
这里的问题是您正在比较characters
no 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);
}
}
推荐阅读
- c# - 如何在 Windows 10 中实现通用访问配置文件 (GAP)?
- python - 将 DataFrame 对象转换为字符串或对齐 DataFrame 编码
- c# - 使用 Xamarin.Forms 4.3.0.947036 在没有闪光灯的情况下在 Android 和 iOS 上实现正常和暗模式
- reactjs - Passport.js + Express + Next.js + Mongoose -> 本地身份验证不起作用
- python - 如何将以下 if 语句转换为更有效的嵌套 for 循环
- python-3.x - 尝试制作模拟时钟
- ruby - 如何断言表单提交与 capybara 和 minitest 一起使用?
- sql - 收集多个领域的大量数据并获得每家公司平均美元的最佳方法是什么?
- python - 在 Jupyter Notebook 中输出 Pandas 数据框时如何防止垂直滚动条?
- google-data-studio - 如何过滤单个单元格中具有多个值的字段?