Search code examples
cloopsfor-loopc-stringsuppercase

How to append characters to a string array in C


I'm very new to C and I'm trying to write a program that checks if a string contains any uppercase letters, and if it does, prints them out. I'm using https://www.onlinegdb.com/online_c_compiler# as my compiler (cause I don't have access to my personal computer right now) and after a test run, the results are (p.s. I know gets isn't safe):

main.c:16:5: warning: ‘gets’ is deprecated [-Wdeprecated-declarations]
/usr/include/stdio.h:638:14: note: declared here
main.c:(.text+0x26): warning: the `gets' function is dangerous and should not be used.
sTrInG
Contains Uppercase!
Uppercase Letters:0

...Program finished with exit code 0
Press ENTER to exit console.

In this case, I expect an output something like this:

Contains Uppercase!
Uppercase Letters: TIG

My script:

#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main()
{
    char str[100];
    gets(str);
    int containsUpper = 0;
    char upperLetters[100] = {0};
    for (int i=0; i < strlen(str); i++) {
        if (islower(str[i])) {
            continue;
        } else {
            containsUpper = 1;
            upperLetters[i] = str[i]; // is this the bad line?
        }
    }
    if (containsUpper) {
        printf("Contains Uppercase!\n");
        printf("Uppercase Letters:");
        printf("%zu\n", strlen(upperLetters)); // prints 0 so upperLetters is empty..?
        for (int i=0; i < strlen(upperLetters); i++) {
            printf("%c", upperLetters[i]);
        }
    } else {
        printf("Does not contain Uppercase!");
    }
    return 0;
}

Solution

  • You want the loop to be:

    int i, j=0;
    for (i=0; i < strlen(str); i++) {
        if (isupper((unsigned char)str[i])) {
            upperLetters[j++] = str[i];
        }
    }
    upperLetters[j]= '\0';
    containsUpper = (j>0);
    

    That is, keep a separate index of the upper letters array. And don't forget to terminate it.

    A better way for the loop is:

    int i, j, k;
    for (i=0, j=0, k=strlen(str); i < k; i++) {
    

    as this calls strlen only once.

    EDIT: As user LxerLx pointed out, a character which is not a lower case letter does not have to be an upper case letter. I updated the loop for this.