Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

printf - Is it possible to print out only a certain section of a C-string, without making a separate substring?

Say I have the following:

char* string = "Hello, how are you?";

Is it possible to print out only the last 5 bytes of this string? What about the first 5 bytes only? Is there some variation of printf that would allow for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Is it possible to print out only the last 5 bytes of this string?

Yes, just pass a pointer to the fifth-to-the-last character. You can determine this by string + strlen(string) - 5.

What about the first 5 bytes only?

Use a precision specifier: %.5s

#include <stdio.h>
#include <string.h>
char* string = "Hello, how are you?";

int main() {
  /* print  at most the first five characters (safe to use on short strings) */
  printf("(%.5s)
", string);

  /* print last five characters (dangerous on short strings) */
  printf("(%s)
", string + strlen(string) - 5);

  int n = 3;
  /* print at most first three characters (safe) */
  printf("(%.*s)
", n, string);

  /* print last three characters (dangerous on short strings) */
  printf("(%s)
", string + strlen(string) - n);
  return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...