Title Case function in C I've written the following function in C which shall take as input a character array (decayed to a char * of course), and mutate the string into a title-cased string in the form "this is a string" -> "This Is A String".

void title_case(char str[])
{
    assert(str);
    size_t i;
    str[0] = toupper((int) str[0]);
    if(strlen(str) == 1) return;
    for(i = 1; i &lt; strlen(str); ++i)
    {
        str[i] = tolower((int)str[i]);
        if(str[i -1] == ' ')
        {
            str[i] = toupper((int)str[i]);
        }
    }
    return;
}


Please provide any feedback you see fit. Is there a more concise way to do this? Is array bracket notation the most clear way?

Driver:

#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;assert.h&gt;
#include &lt;ctype.h&gt;

void title_case(char str[]);
int main(void)
{
    char sentence[] = "this is a SeNTeNce.";
    title_case(sentence);
    printf("%s\n", sentence);
    return 0;
}
In the context of function parameter passing, char* and char[] are equivalent (because char[] decays to char*).

Anyway, I would rather use title_case(char* s) because it more clearly expresses the truth: what you really get within the function is a pointer to the first character of the array.
Accepting char* as string parameter implicitly suggests that the passed string will be '\0'-terminated. As you probably know, there are many known security issues with this.
If that's not the case, that means if you cannot guarantee the '\0'-ending always, consider passing the string length also, for ex.: 
title_case(char* s, size_t len) 
The cast from char to int (int)s[0] should not be needed, because conversion from smaller to the bigger integral type is always done implicitly and should trigger no warning on any compiler I know.


4.The strlen() in this loop for(i = 1; i &lt; strlen(str); ++i) is called on every iteration, so the overall complexity will be quadratic. The common practice to avoid this is to store length into a variable and then use it, like:

size_t len = strlen(str);
for (i = 1; i &lt; len; ++i) ...



The more concise way with linear complexity would be something like this


>

#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;ctype.h&gt;

void title_case(char *s)
{
    if (s == NULL) return;

    for (char *p = s; *p != '\0'; ++p)
        *p = (p == s || *(p-1) == ' ') ? toupper(*p) : tolower(*p);
}

int main()
{
    char s[] = "this is some     title";
    title_case(s);
    printf("%s\n", s);
}


Note: In the boolean expression p == s || *(p-1) == ' ' short-circuit evaluation capability of C/C++ is used: if p==s is true, then *(p-1) is not evaluated. Otherwise we would dereference invalid pointer -> which would lead to undefined behaviour.

Edited: Emphasize quadratic complexity issue, as proposed in comments by @sudo