简体   繁体   中英

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

I am not experienced in C so please help me in clear way.

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.

#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++;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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