使用String逐字打印(换行)

时间:2017-06-03 10:45:22

标签: c gcc

我试图逐个打印一串单词(个别)但是我被困在这里...否则会打印整个字符串四次但这不是逻辑我打算。

#include <stdio.h>
#include <string.h>

int main()
{
    char str[] = "Hello! A_word and Another_word";
    unsigned int count = 0;
    unsigned int str_size = strlen(str);

    do {
        while(str[count++] != 32) {
            // more codes needed here I think to manipulate one word
        }
        // print one word and proceed
        printf("%s\n", str);
    } while(count < str_size);

    return(0);
}

输出应为:

您好!
A_word

Another_word

2 个答案:

答案 0 :(得分:2)

基本上您需要在换行符(' ')中转换空格('\n')。

#include <stdio.h>
#include <string.h>

int main()
{
    char str[] = "Hello! A_word and Another_word";
    unsigned int str_size = strlen(str);

    for(int i = 0; i < str_size; i++) {
        if(str[i] == ' ') printf("\n");
        else printf("%c", str[i]);
    }

    return 0;
}

您还可以使代码更简单,假设字符串是以'\0'字符结尾的字符数组。

#include <stdio.h>

int main() {
    char str[] = "Hello! A_word and Another_word";

    for(int i = 0; str[i] != '\0'; i++) {
        if(str[i] == ' ') printf("\n");
        else printf("%c", str[i]);
    }

    return 0;
}

答案 1 :(得分:0)

我建议您使用strtok_r(),这是您的代码:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char str[] = "Hello! A_word and Another_word";
    char *token;
    char *saveptr = str;
    while (1) {
        token = strtok_r(saveptr, " ", &saveptr);
        if (token == NULL) {
            break;
        }
        printf("%s\n", token);
    }
    return(0);
}