Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The simplest way of printing a portion of a char[] in C

Let's say I have a char* str = "0123456789" and I want to cut the first and the last three letters and print just the middle, what is the simplest, and safest, way of doing it?

Now the trick: The portion to cut and the portion to print are of variable size, so I could have a very long char*, or a very small one.

like image 727
Edu Felipe Avatar asked Nov 01 '08 22:11

Edu Felipe


People also ask

What does char * [] mean in C?

char* means a pointer to a character. In C strings are an array of characters terminated by the null character.

How do you print only part of a string in C?

You can use strncpy to duplicate the part of your string you want to print, but you'd have to take care to add a null terminator, as strncpy won't do that if it doesn't encounter one in the source string.


2 Answers

You can use printf(), and a special format string:

char *str = "0123456789"; printf("%.6s\n", str + 1); 

The precision in the %s conversion specifier specifies the maximum number of characters to print. You can use a variable to specify the precision at runtime as well:

int length = 6; char *str = "0123456789";     printf("%.*s\n", length, str + 1); 

In this example, the * is used to indicate that the next argument (length) will contain the precision for the %s conversion, the corresponding argument must be an int.

Pointer arithmetic can be used to specify the starting position as I did above.

[EDIT]

One more point, if your string is shorter than your precision specifier, less characters will be printed, for example:

int length = 10; char *str = "0123456789"; printf("%.*s\n", length, str + 5); 

Will print "56789". If you always want to print a certain number of characters, specify both a minimum field width and a precision:

printf("%10.10s\n", str + 5); 

or

printf("%*.*s\n", length, length, str + 5); 

which will print:

"     56789" 

You can use the minus sign to left-justify the output in the field:

printf("%-10.10s\n", str + 5); 

Finally, the minimum field width and the precision can be different, i.e.

printf("%8.5s\n", str); 

will print at most 5 characters right-justified in an 8 character field.

like image 90
Robert Gamble Avatar answered Oct 08 '22 02:10

Robert Gamble


Robert Gamble and Steve separately have most of the pieces. Assembled into a whole:

void print_substring(const char *str, int skip, int tail) {     int len = strlen(str);     assert(skip >= 0);     assert(tail >= 0 && tail < len);     assert(len > skip + tail);     printf("%.*s", len - skip - tail, str + skip); } 

Invocation for the example:

print_substring("0123456789", 1, 3); 
like image 39
Jonathan Leffler Avatar answered Oct 08 '22 01:10

Jonathan Leffler