Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print only certain parts of a string?

Tags:

c

string

printf

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?

like image 728
Paul Manta Avatar asked Oct 20 '11 20:10

Paul Manta


2 Answers

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.

like image 117
Blagovest Buyukliev Avatar answered Sep 21 '22 20:09

Blagovest Buyukliev


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 ] ); 
like image 44
Bob Kaufman Avatar answered Sep 20 '22 20:09

Bob Kaufman