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 < 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 <stdio.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
void title_case(char str[]);
int main(void)
{
char sentence[] = "this is a SeNTeNce.";
title_case(sentence);
printf("%s\n", sentence);
return 0;
}