c - 使用 String 逐字打印(换行)

标签 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);
}

输出应该是:

你好!
一个字

另一个词

最佳答案

基本上您需要在换行符 ('\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;
}

关于c - 使用 String 逐字打印(换行),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44343053/

相关文章:

gcc - 在编译期间告诉 ld 在哪里寻找依赖的共享库

linux - 如何在 Linux 中生成核心转储文件?

c - 什么是调度表?我如何在 C 中实现它?

c - 从 .c 文件生成 .i 文件

c - 链接 C 中的库,未识别的引用

c - 用空格分割字符串

c - getopt 中的 opterr 声明

macos - opencv 用 clang 编译好,用 gcc 编译不行 os x 10.9

c++ - 什么样的 GCC 优化可能会根据是否打印来更改 double?

c - 在 arm-none-eabi-gcc 中使用显式字节顺序进行复制的优化