简体   繁体   English

如何在C中打印字符串的一部分

[英]How print a part of string in C

I would like to print a part of string. 我想打印一部分字符串。 My program should print characters from begin until in string will be for example character like this: \\" 我的程序应该从头开始打印字符,直到字符串中的字符都是这样的字符:\\“

For example: 例如:

char* text = "abcdef\"ghij";

And I would like to get: abcdef 我想得到: abcdef

I am not experienced in C so please help me in clear way. 我没有C方面的经验,请明确帮助我。

Use * field width to select the number of characters to print: 使用*字段宽度选择要打印的字符数:

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

char* text = "abcdef\"ghij";
printf("%.*s\n", (int) (strchr(text, '"') - text), text);

Print char by char in a loop until either the stop character occurs or the current character becomes falsy, ie is the null terminator. 在一个循环中逐字符打印char,直到出现终止字符或当前字符变为伪(即空终止符)为止。

#include <stdio.h>

char* text = "abcdef\"ghij";
char stop = '"';

for (char *i = text; *i && *i != stop; i++)
    putc(*i, stdout);
int i=0;    

while(i < sizeof(text))
  {
     if(text[i] == '\"')
    break;
 else 
    printf("%c",text[i]);

  i++;
  }

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

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