c - 计算具有多个空格的字符串中的单词
问题描述
我需要可以计算字符串中的单词而不计算它们之间的多个空格的代码。
我可以编写一个程序来计算单词之间只有 1 个空格,但我不知道当它超过 1 个空格时我应该如何编码。我想像一个for
循环来检查它之前的字符是否是一个空格,但我不知道该怎么做。我想提一下,我是 C 语言的初学者。
#include <stdio.h>
#include <string.h>
int main()
{
char s[200];
int count = 0, i;
printf("enter the string: ");
fgets(s,200,stdin);
for (i = 0;s[i] != '\0';i++)
{
if (s[i] == ' ')
count++;
}
printf("number of words in given string are: %d\n", count+ 1);
return(0);
}
解决方案
您可以引入一个标志来判断前一个字符是否为空格。就像是:
#include <stdio.h>
#include <string.h>
int main()
{
char s[200];
int count = 0, i;
int last_was_space = 1;
printf("enter the string: ");
fgets(s,200,stdin);
for (i = 0;s[i] != '\0';i++)
{
if (s[i] == ' ')
{
if (!last_was_space)
{
count++; // Only count when last char wasn't a space
last_was_space = 1;
}
}
else
{
// Update flag (unless this char is a newline)
if (s[i] != '\n') last_was_space = 0;
}
}
if (!last_was_space) ++count; // Count the last word if there wasn't a space before
printf("number of words in given string are: %d\n", count);
return(0);
}
推荐阅读
- javascript - 在JS中将字符串转换为函数
- c# - 使用 mvvm 在 WPF 数据网格中的行单击事件
- c# - C# 字符串数组元素不更新
- java - 如何在 hql 请求中正确调用枚举方法?numberClass 和 symbolClass 是一个枚举
- java - 在 Java 中生成 XML 有效负载的最有效方法
- java - Android ListAdapter.getItemCount() 总是返回 0
- javascript - 获取用户在 EJS 中选择的表详细信息?
- javascript - cookie 何时被视为第三方 cookie?
- sql - 编写查询以查找从 10 月到 11 月因购买而产生的收入变化
- r - Datatable 显示 empy selectInput 而默认选择值