我试图一个接一个地(单个)打印一串单词,但我被困在这里……否则会打印整个字符串四次,但这不是我想要的逻辑。
#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/