Wednesday, September 22, 2010

printf for substring

There are situations when you don't want to print whole string. The first time when I was in need of such functionality was when I wanted to print ANSI_STRING in driver level. This special data structure does not put a trailing '\0' at end of every string. Rather Each string has a field that store the length of the buffer. If you find yourself in any such situation fear not =) printf can output a substring as well. All you need is the length of substring. Here is the code for that... enjoy!!!


#include "stdio.h"

int main ()
{
char * hello = {"Hello World! How are you doing?"};
int len = 12;
printf("%.*s\n", len, hello);
return 0;
}


Here is the output of this function:

Hello World!