c - 如何在每个单词之前打印字符串中每个单词的长度
问题描述
我想打印字符串中每个单词的长度。
我试过但没有得到正确的答案。运行代码后,它将在单词之后打印每个单词的长度,而不是在每个单词之前打印。
char str[20] = "I Love India";
int i, n, count = 0;
n = strlen(str);
for (i = 0; i <= n; i++) {
if (str[i] == ' ' || str[i] == '\0') {
printf("%d", count);
count = 0;
} else {
printf("%c", str[i]);
count++;
}
}
我除了输出是1I 4Love 5India
,但实际输出是I1 Love4 India5
。
解决方案
您想在打印单词之前计算并打印每个单词的长度。
这是一个简单的解决方案,它是一个strcspn()
应该更经常使用的标准函数:
#include <stdio.h>
#include <string.h>
int main() {
char str[20] = "I Love India";
char *p;
int n;
for (p = str; *p;) {
if (*p == ' ') {
putchar(*p++);
} else {
n = strcspn(p, " "); // compute the length of the word
printf("%d%.*s", n, n, p);
p += n;
}
}
printf("\n");
return 0;
}
推荐阅读
- r - 如何删除R中以下列中右数(0)的第二个数字?200517302 200517801 200519101 200519702 200521002 200521205
- javascript - 不等式不显示正确的输出,JS
- node.js - 电子锻造启动被 Gulp 破坏
- javascript - 如果 variable=string 总是返回 true
- python - 包含字典的 pyspark 数据框列的总和
- html - Angular 6:Mat-card 使用固定道具使页面内容可滚动
- ios - Phonegap 需要 IOS 密钥
- matlab - Julia vs. MATLAB - 距离矩阵 - 运行时测试
- python - 使用 Keras 的简单线性回归
- wordpress - WP如何显示他“2个月前”发表的帖子