vivek
vivek

Reputation: 587

How to print only some characters in C?

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?

Upvotes: 1

Views: 2769

Answers (4)

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

Upvotes: 3

David C. Rankin
David C. Rankin

Reputation: 84642

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.

Upvotes: 0

0___________
0___________

Reputation: 68013

for example substring extraction function (extracts substring to the buff)

char *strpart(char *str, char *buff, int start, int end)
{
    int len = str != NULL ? strlen(str) : -1 ;
    char *ptr = buff;

    if (start > end || end > len - 1 || len == -1 || buff == NULL) return NULL;

    for (int index = start; index <= end; index++)
    {
        *ptr++ = *(str + index);
    }
    *ptr = '\0';
    return buff;
}

Upvotes: 0

Geo
Geo

Reputation: 155

- is a printf formater for justification, not precision.

What you want is the . formater which is used for precision :

printf("%.5s", arr);

This will print the first 5 elements of arr.

If you want to learn more about printf formaters, take a look at this link.

Upvotes: 2

Related Questions