Aneta Kožoušková Aneta Kožoušková - 1 month ago 6
C Question

c - How to make whole string uppercase, if it contains numbers?

So I need to make a string uppercase + remove spaces from it. It however doesn't work, if the string contains numbers, the final print prints some non-ascii chars. How should I make it work? I tried to do it with functions

isalpha()
and
isdigit()
, but the result is the same.

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

int main(){
int i = 0;
char c[100];
char str[] = "Hello8 world";

while(str[i]){
if (str[i]!=' '){
if (str[i] >= '0' && str[i] <= '9'){
c[i]=str[i];
}
else{
c[i]=(toupper(str[i]));
}
i++;
}
}
printf("%s", c);

return(0);
}

Answer

There are several things wrong here. First, you only advance i inside the if statement, so once you encounter a space, your problem will get stuck in an endlees loop. Second, you assume the index in the source and target string are the same - which is not true, since you're skipping spaces. This will cause the target string to keep unitialized memory - which could be \0 on some platforms, and could just be random junk on others. Instead, you should maintain two index counters, one for the source and one for the target, and explicitly set \0 at the end of the target when you're done:

int i = 0;
int j = 0; /* Target string index */
char c[100];
char str[] = "Hello8 world";

while(str[i]){
    if (str[i]!=' '){ 
        if (str[i] >= '0' && str[i] <= '9'){
            c[i]=str[i];
        }
        else{
            c[j]=(toupper(str[i]));
        }
        j++; /* Target index advance only when it's used */
    }
    i++; /* Source index advanced regardless */
}
c[j] = '\0'; /* Handle the string termination */
printf("%s\n", c);