Print from one position to another - using printf

1.1k Views Asked by At

I want to do the following, taking into account a string as how are you I want to print from a until e ie the word are. I tried this

char str[] = "how are you";
printf("%*.*s\n", 5, 8, str);

Output

how are

Expected output

are

Someone has idea how this can be done?

3

There are 3 best solutions below

0
On

The characters in the string are indexed from 0, so the a is at index 4. By passing &str[4] to printf, the printf will start at the a, and print as many characters as specified by the precision.

printf("%.*s\n", 3, &str[4]);
13
On

You are specifying field width and number of chars to print. However, the string always starts from the pointer as passed, there is no "start offset" specifier, as that would be unnecessary. See here for the format specifiers.

For your code, that would be printf("%.*s", width, str + start)

Note that &str[start] is identical.

0
On

try using this code

printf("%.*s\n", 3, &str[4]);