首页 > 解决方案 > 如何在每个单词之前打印字符串中每个单词的长度

问题描述

我想打印字符串中每个单词的长度。

我试过但没有得到正确的答案。运行代码后,它将在单词之后打印每个单词的长度,而不是在每个单词之前打印。

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

标签: cstring

解决方案


您想在打印单词之前计算并打印每个单词的长度。

这是一个简单的解决方案,它是一个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;
}

推荐阅读