Question: I have an array:

```
char arr[]="This is the string";

```

For instance, if I want to print only first 5 characters of that string, I have tried the following:

```
printf("%-5s",arr);

```

But it is printing whole string. Why?

Answer: 
You can use `%.*s`, it takes size of intended bytes to be printed and pointer to char as arguments when using with `printf`. For example,

```
// It prints This
printf("%.*s", 4, arr);

```

> 
> But it is printing whole string. Why?
> 
> 
> 

You are using `%-5s` meaning the `-` left-justifies your text in that field.

---

En passant, the output cannot be achieved by using the accepted answer as simply as the code snippet, even if it may be seemed derisively.

```
int i;
char arr[]="This is the string";

for (i = 1; i < sizeof(arr); ++i) {
    printf("%.*s\n", i, arr);
}

```

Output:

```
T
Th
Thi
This
This 
This i
This is
This is 
This is t
This is th
This is the
This is the 
This is the s
This is the st
This is the str
This is the stri
This is the strin
This is the string

```
You can do it quite simply in a number of ways. With a loop, looping the number of times desired, picking off chars each time, you can walk a pointer down the string an temporary nul-terminate after the 5th character, or you can simply use `strncpy` to copy 5 chars to a buffer and print that. (that is probably the simplest), e.g.

```
#include <stdio.h>
#include <string.h>

int main (void)
{
    char arr[]="This is the string",
        buf[sizeof arr] = "";      /* note: nul-termination via initialization */

    strncpy (buf, arr, 5);

    printf ("'%s'\n", buf);

    return 0;
}

```

**Example Use/Output**

```
$ ./bin/strncpy
'This '

```

Look things over and let me know if you have any questions.