Search code examples
cfor-looptoupper

Change every other alpha character in a string to uppercase using C


Would someone kindly steer me in the proper direction with the following code I have written. Basically I'm trying to have every other character in a string be printed in an uppercase letter, all while not taking spaces or other non alpha characters into consideration.

example: string input = "thanks for the add" should print as "ThAnKs FoR tHe AdD"

int main (void) 
{
    char* input = GetString();
    if (input == NULL)
        return 1;
    for (int i = 0, x = strlen(input); i < x; i+=2)
        input [i] = toupper(input[i]);
    printf("%s\n", input);
    return 0;
}

note: I'm new to computer science and am currently taking CS50x through edx.org


Solution

  • Just use isalpha to ignore other kinds of characters:

    #include <string.h>
    #include <stdio.h>
    #include <ctype.h>
    int main (void) 
    {
        char input[] = "thanks for the add";
        int  alpha_count = 0;
        for (int i = 0, x = strlen(input); i < x; i++) {
          if (isalpha(input[i])) {
            if (alpha_count++ % 2 == 0 ) 
              input [i] = toupper(input[i]);
          }   
        }   
        printf("%s\n", input);
        return 0;
    }