7

I have a string const char[15] and I want to print it like this:

Label-one: characters [0,13)
Label-two: characters [13, 15)

How can I print only certain parts of the string?

Paul Manta
  • 30,618
  • 31
  • 128
  • 208

2 Answers2

17
printf("Label-one: %.*s", 13, str);
printf("Label-two: %.*s", 2, str + 13);

@Bob's answer is also acceptable if these lengths are constant, but in case the lengths are determined at runtime, this is the best approach since it parametrises them.

Blagovest Buyukliev
  • 42,498
  • 14
  • 94
  • 130
8
printf( "%.13s", labelOne );   // stops after thirteen characters.
printf( "%.3s", &labelOne[ 13 ] );  // prints three characters of the string that starts at offset 13

I'm noticing a possible fencepost error/inconsistency in your question or my answer, depending on your point of view. The correct answer for the second example may be:

printf( "%.3s", &labelOne[ 12 ] ); 
Bob Kaufman
  • 12,864
  • 16
  • 78
  • 107
  • 4
    A small stylistic advice: `labelOne + 13` seems neater and more natural than `&labelOne[13]`. – Blagovest Buyukliev Oct 20 '11 at 20:52
  • @Blagovest -- Force of habit I suppose. I've gone back and forth on the issue, and to your point, your format is much more common today. When I started developing in C lo these many years, the &str[ offset ] format seemed to be more commonplace. – Bob Kaufman Oct 20 '11 at 21:12