C program to print the length of a String using %n format specifier

Given string str. The task is to find the length of the string using %n format specifier

Examples:




Input: Geeks For Geeks
Output: 15

Input: Geeks
Output: 5

Appropach:

To find the length of string, we use special format specifier “%n” in printf function. In C printf(), %n is a special format specifier which instead of printing something causes printf() to load the variable pointed by the corresponding argument with a value equal to the number of characters that have been printed by printf() before the occurrence of %n.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to print
// the length of a String
// using %n format specifier
  
#include <stdio.h>
  
// Driver code
int main()
{
    char str[100] = "Geeks for Geeks";
    int len = 0;
  
    printf("%s%n", str, &len);
    printf(" = %d", len);
  
    return 0;
}

chevron_right


Output:

Geeks for Geeks = 15


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.