OneBite.Dev - Coding blog in a bite size

convert a string to lowercase in C

Code snippet on how to convert a string to lowercase in C

  #include <stdio.h>
  #include <ctype.h>
  #include <string.h>
  int main()
  {
  char string[80];
 
  strcpy(string, "ABCdef");
 
  printf("String before converting to lowercase: %s\n", string);
 
  for (int i = 0; i < strlen(string); i++)
  {
     string[i] = tolower(string[i]);
  }
 
  printf("String after converting to lowercase: %s\n", string);
 
  return 0;
  }

This code involves three C libraries - stdio.h, ctype.h and string.h. Firstly, a string of characters is declared using char string[80] and is then initialized with a value using strcpy. This is done with the value “ABCdef” which is then printed to the screen with printf. A loop is then initialized that takes each character of the string one by one and changes its case to lowercase with the tolower() function. After the loop completes, the new lowercase string is printed back to the screen. Finally, main() returns 0 meaning the code has been successfully executed.

c