Search code examples
carraysstringfunctiontoupper

C function to capitalize first letter of words in an array


I'm pretty new to C and am hitting a wall when creating the below function. I want to use this function to make the first letter of a word upper case for a static character array (char string[]. It looks ok to my eye, but I'm getting some syntax errors which are probably pretty basic. compiler errors:

error: invalid conversion from const char' toconst char*' initializing argument 1 of `size_t strlen(const char*)' assignment of read-only location

  void Cap(char string[]){
    int i;
    int x = strlen(string);
    for (i=1;i<x;i++){
         if (isalpha(string[i]) && string[i-1] == ' '){
         // only first letters of a word.
             string[i]= toupper(string[i]);
         }if (isalpha(string[0]))
                        {
                          string[0]=toupper(string[0]);
                        }
         }
}

Solution

  • I took your code and tried to compile it. Well, it would be nice to see compilable code the next time. Here is one with comments.

    #include <stdio.h> // Now I am able to use printf.
    #include <string.h> // I was not able to use strlen without this...
    
    void Cap(char string[]){     
        int i;
        int x = strlen(string); // You want to get the length of the whole string.
        for (i=1;i<x;i++){
             if (isalpha(string[i]) && string[i-1] == ' '){ 
             // only first letters of a word.
                 string[i]= toupper(string[i]);
             }
        }
    }
    
    main(){
      char string[] = "text with lowercase words.";
      Cap(string);
      printf("%s",string);
    };
    

    Still the first word of the text is lowercase. This is a task for you.