c - 数数 C 编程中字符串中的单词数(我收到空字符常量错误)
问题描述
我的代码是不计算字符串中的单词。但是 (a[i]=='') 显示空字符常量错误
#include <stdio.h>
int main() {
char a[20];
int i,c1=0,c2=0;
scanf("%[^\n]",a);
for(i=0;a[i]!='\0';i++)
{
c1++;
if(a[i]=='')
c2++;
}
printf("%d\n",c1);
printf("%d",c2+1);
return 0;
}
对于输入 - 汤姆在这里
我希望输出为 -11 3
编译错误-在函数'main'中:
prog.c:10:15:错误:空字符常量 if(a[i]=='') ^
解决方案
#include <stdio.h>
int main() {
char str[50];
int i, numberOfWords=0;
gets(str);
for(i=0; str[i]!='\0'; i++) {
if(str[i] == 32) //ascii code of space is 32
numberOfWords++;
}
printf("number of words = %d\n", numberOfWords + 1);
//adding 1 to numberOfWords because if there are two words, there will be 2-1=1 space between them. eg= "Hello World"
return 0;
}
推荐阅读
- ios - 使用 CFBundleDocumentTypes 通过 Share Sheet 在我的应用程序上打开图像
- c++ - shared_ptr 内 string_view 的返回值优化
- c# - 如何在 JB Rider for Xamarin.Forms 中启用智能感知?
- php - 如何不在 Laravel 路由中使用完整的控制器路径
- php - 获取“Cookie “PHPSESSID” 已因无效域而被拒绝。” 当一个模块调用另一个模块时在控制台上
- python - 我在让这个网络爬虫在 django 上启动时遇到问题。输入“python manage.py runserver”时终端出现错误
- python - 如何在 smtplib 中更改字体
- javascript - 当我尝试使用 if 语句过滤它们时,显示从 JavaScript 到 HTML 的数据,加载并在 1 秒后消失。为什么?
- r - 绘制决策树分类器
- azure - Spark, wasb and Jetty 11