2013/11/20

"%.*s" in printf()

Background

Currently, I am dealing with regex example in C.  There is a abnormal printf command.
......
printf ("'%.*s' (bytes %d:%d)\n", (finish - start),  to_match + start, start, finish);
......
Ouput:
$& is '1 is nice 2' (bytes 5:16)
I am wondering why there are 3 "%s" format options but there are 4 parameters to map those options.

Dig deeper...

To make the story short, "%.*s" is where the amazing happen. This option take 2 arguments: length of the string and the starting point of a string. (XXX: so ?) OK. Take a look the example code below.

#include <stdio.h>

int main(int argc, const char *argv[])
{
        char a[] = "0123456789";

        int len, offset;
        len = 4;

        for (offset = 0; offset < 3; offset++) {
                printf("%.*s\n", len, a + offset);
        }

        return 0;
}

Output:
0123
1234
2345

In other word, "%.*s" allows you to print a subset of a string without doing tedious jobs like following.

char *b = (char *) malloc(4+1);
memcpy(b, a+offset, len);
b[len+1] = '\0';
printf("%s\n",b);



沒有留言:

張貼留言