OneBite.Dev - Coding blog in a bite size

format a string in C

Code snippet on how to format a string in C

  #include <stdio.h>
  #include <string.h>
  int main() {
    char str[] = "This is a string";
    char format[] = "%s";

    printf(format, str);
    return 0;
  }

This code is written in C language and it will format a string. First, it includes both the stdio.h and string.h header files, which are necessary for running the code. Then, a character array called str is declared and contains the string “This is a string”. Next, another character array format is declared which contains the formatting value %s, which is a placeholder for a string. To display the string, the printf() function is used. The first argument in the printf() function is the format array which contains the placeholder for a string, and the second argument is the string itself, which is the str array. Lastly, the program returns the value 0. Run the code and it will print out the contents of the str array.

c