How to capitalize the first letter of each word in a string with C

1 Answer

0 votes
#include <stdio.h>
#include <ctype.h>
#include <string.h>

void capitalizeFirstLetter(char *str) {
    int length = strlen(str);

    // Check if the first character is lowercase and capitalize it
    if (length > 0 && islower(str[0])) {
        str[0] = toupper(str[0]);
    }

    // Iterate through the rest of the string
    for (int i = 1; i < length; i++) {
        // If the current character is a space and the next character is lowercase
        if (str[i] == ' ' && islower(str[i + 1])) {
            str[i + 1] = toupper(str[i + 1]);
        }
    }
}

int main() {
    char str[] = "c programming language";
    
    capitalizeFirstLetter(str);
    
    printf("%s\n", str);
    
    return 0;
}    
      
       
/*
run:
    
C Programming Language
   
*/

 



answered Jan 26, 2017 by avibootz
edited Feb 1, 2025 by avibootz

Related questions

...