c - 如何计算仅以特定单词为后缀且仅作为后缀的单词数量?
问题描述
所以我有这个,我想:
For the word "are":
caramare
aresdn
lasrare
aresare
mare
We have n=3
因为只有 3 个单词以我们的特定单词结尾,并且只有一次。如果我读错了单词,比如“ares”,it will break the program.
那是为什么呢?需要从以下位置启动程序:
n=.....;
for(i=1;i<=11;i++)
{ cin>>s; | scanf(“%s”,s);
............
}
这是我尝试过的:
#include <stdio.h>
#include <string.h>
int main()
{
char s[20][20];
int n=0;
int i;
for(i=1;i<=11;i++)
{
scanf("%s",s);
if(strcmp ( strstr("are",s[i]) ,"are") ==0 )
{
n++;
}
}
printf("%d",n);
}
解决方案
一个问题是,strstr
如果找不到针头,则返回 NULL。然后你传递一个 NULL 指针,strcmp
它会出错。
你需要像这样拆分它:
char* tmp = strstr("are",s[i]);
if (tmp)
{
if (strcmp ( tmp ,"are") ==0 )
{
n++;
}
}
和这个
char s[20][20];
应该是:
char s[20];
并且请永远,永远不要做scanf("%s",s);
Always - 就像always,allways,allways - 设置一个限制 - 就像scanf("%19s",s);
用户不能溢出你的输入缓冲区一样。
推荐阅读
- sql - 如何使用 oracle 查找包含特定字符串值的列名
- android - MVVMCross 6.4.3 还原未按预期工作
- javascript - 如何在单选按钮中仅选择一个选项后发布两个属性的数据?
- sql - 查询优化:SUMIF 和 CASE WHEN
- python - 如何在单个函数中递归计算 AVL-Tree 节点的余额?(Python)
- amazon-web-services - Terraform 启动源实例时出错:可用区中的 InsufficientInstanceCapacity
- javascript - 使用 async/await 在 promise 中捕获错误
- java - JTable Left 和 Upper Lines 不可见
- visual-studio-code - 输入时,vscode中光标自动向左移动
- security - Ansible sysctl 尝试重新加载 ipv6,即使禁用了 ipv6