OneBite.Dev - Coding blog in a bite size

convert a string to uppercase in C

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

  #include <stdio.h>
  #include <string.h>
  #include <ctype.h>
  
  int main(void) {
    char str[] = "Hello World";
    int i;
    
    for (i = 0; i < strlen(str); i++) {
      str[i] = toupper(str[i]);
    }
    
    printf("%s\n", str);
    return 0;
  }

This example code shows how to convert a string to all uppercase letters. It starts by including three libraries: stdio.h, string.h and ctype.h. stdio.h is for the printf function, string.h is for the strlen function, and ctype.h is for the toupper function. Next, the string “Hello World” is declared, and the for loop ensures that all of the characters of the string are looped through. The toupper function then converts each character in the string to its uppercase equivalent. Lastly, the uppercased string is printed using the printf function and the program returns a value of 0, which indicates success.

c