简体   繁体   English

一次打印一个 C 字符串的一个字符

[英]Print a single character of a C string at a time

I have a variable: char *string and a for loop with int i=0 to len(string) .我有一个变量: char *string和一个for循环, int i=0len(string)

Inside the loop, it prints &string[i] .在循环内部,它打印&string[i]

Trying to get it to show only a single character, but if I have a string "red", it would print:试图让它只显示一个字符,但如果我有一个字符串“红”,它会打印:

red
ed
d

In order to print a character with printf() , you need to use the appropriate format specifier, %c , like this:为了使用printf()打印字符,您需要使用适当的格式说明符%c ,如下所示:

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

int main(void)
{
  char* string = malloc(sizeof(char) * 16);
  strcpy(string, "red");
  for(size_t i = 0; i < strlen(string); ++i)
  {
    printf("%c\n", string[i]);
  }
  return 0;
}

Output:输出:

r
e
d

As @jonathanLeffler commented, putchar(string[i]);正如@jonathanLeffler 所评论的, putchar(string[i]); would do the trick as well.也会这样做。


In your attempt, what went wrong is this line * :在您的尝试中,出错的是这一行*

printf("%s\n", &string[i]);

which, because of the format specifier %s for strings, it will print the whole string until its end (NULL terminator is met), starting from the i -the character.其中,由于字符串的格式说明符%s ,它将打印整个字符串,直到它的结尾(遇到 NULL 终止符),从i -the 字符开始。


Reversed engineered from the sample output of yours and post.根据您和帖子的示例输出进行逆向工程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM