question
question

Reputation: 410

Printing specific character from a string in C

I'm working on prefixing of a string for example : com should give me c co com. I know to print a character in this was printf("%.5s",string) to print the first five values. I want to do this in a loop instead of 5 how can I replace it with i which is a incrementing value,something like this printf("%.is",string). how can I obtain this?

Upvotes: 0

Views: 5117

Answers (3)

haccks
haccks

Reputation: 106012

Try this:

char s[] = "com";  
for(size_t i = 1; i <= strlen(s); i++)
{
    for(int j = 0; j < i; j++)  
         printf("%c", s[j]);
    printf(" ");  
}

Upvotes: 0

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

This is the simplest way of achieving what you want.

printf("%.*s\n", i, string);

If you want to generate the format string, you can do it too

char format[100]; /* the size should be estimated by you */

snprintf(format, sizeof(format), "%%.%ds", i);
printf(format, string)

check the snprintf() return value to ensure that the string was not truncated, if you choos a reasonable size for the format string it will be unlikely, but you should check anyway.

Above, the format specifier means

  • A literal "%"
  • Then a "."
  • Then the integer "%d"
  • Then the letter "s"

so the resulting string will be the format string you need to pass to printf().

Upvotes: 1

M Oehm
M Oehm

Reputation: 29126

In printf format specifiers, all field widths (before the dot) and precisions (after the dot) can be given as asterisk *. For each asterisk, there must be one additional int argument before the printed object.

So, for your problem:

printf("%.*s", i, string);

Note that the additional parameter must be an int, so if you have another integer type, you should cast it:

size_t len = strlen(len);
if (len > 2) printf("%.*s", (int) (len - 2), string);

Upvotes: 5

Related Questions