How to convert a string to title case in C

3 Answers

0 votes
#include <stdio.h>

void to_title_case(char str[]) {
    for (int i = 0; str[i] != '\0'; i++) {
        if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) {
            if (i == 0 || str[i - 1] == ' ') {
                if (str[i] >= 'a' && str[i] <= 'z') {
                    str[i] = str[i] - 32;
                }
            }
            else {
                if (str[i] >= 'A' && str[i] <= 'Z') {
                    str[i] = str[i] + 32;
                }
            }
        }
    }
}

int main(void)
{
    char str[] = "c is a General-purpose computer PROgramming LANGuage";

    to_title_case(str);

    puts(str);

    return 0;
}




/*
run:

C Is A General-purpose Computer Programming Language

*/

 



answered Jul 25, 2022 by avibootz
edited Jul 29, 2022 by avibootz
0 votes
#include <ctype.h>
#include <stdio.h>

void toTitleCase(char *str) {
    int newWord = 1;

    while (*str) {
        if (isspace((unsigned char)*str)) {
            newWord = 1;
        } else {
            if (newWord) {
                *str = toupper((unsigned char)*str);
                newWord = 0;
            } else {
                *str = tolower((unsigned char)*str);
            }
        }
        str++;
    }
}

int main() {
    char str[] = "c is a General-purpose computer PROgramming LANGuage";
    
    toTitleCase(str);
    
    printf("%s\n", str);
    
    return 0;
}



/*
run:
 
C Is A General-purpose Computer Programming Language
 
*/

 



answered Apr 17 by avibootz
0 votes
#include <ctype.h>
#include <stdio.h>

void toTitleCase(char *str) {
    int newWord = 1;

    while (*str) {
        if (isspace((unsigned char)*str) || *str == '-' || *str == '\'') {
            newWord = 1;
        } else {
            if (newWord) {
                *str = toupper((unsigned char)*str);
                newWord = 0;
            } else {
                *str = tolower((unsigned char)*str);
            }
        }
        str++;
    }
}

int main() {
    char str[] = "c is-a General-purpose computer'PROgramming LANGuage";
    
    toTitleCase(str);
    
    printf("%s\n", str);
    
    return 0;
}



/*
run:
 
C Is-A General-Purpose Computer'Programming Language
 
*/

 



answered Apr 17 by avibootz
...