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

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

最佳答案

您可以使用strtok asSome programmer dude建议。当strtok修改传递的字符串时,您可能需要复制原始字符串。此外,strtok不是线程安全的,在使用多线程程序时必须用strtok\u r替换。

#include <stdio.h>
#include <stdlib.h>

/* for strtok */
#include <string.h>

int main() {
    char str[20] = "I Love India";
    int n;

    char* tok = strtok(str, " ");

    while (tok != NULL) {
        n = strlen(tok);
        printf("%d%s ", n, tok);
        tok = strtok(NULL, " ");
    }

    return EXIT_SUCCESS;
}

07-25 23:45
查看更多