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?


Solution 1:

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)\n", string);

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

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

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

Solution 2:

Yes, the last five bytes of that string can be done with:

printf ("%s\n", &(string[strlen (string) - 5]));

The first five can be done with:

printf ("%.5s\n", string);

You can combine the two to get substrings within the string as well. The word how can be printed with:

printf ("%.3s\n", &(string[strlen (string) + 7]));

You do have to be careful that the string is long enough for this to work. Printing the last five characters of a one-character string will cause undefined behaviour since the index ends up at -4. In other words, check the string length before attempting this.