简体   繁体   中英

changing char by subtracting its ASCII code in c language

I am doing some string workshop for my c learning. There is a problem, where you ask for a user input let say "bob" and the code is to lower its ASCII code so it becomes "ana". I am at loss on how I go about doing this. Would it be something like

int main() {
    char str[10];
    char test[10];
    int i;

    printf("Enter a string: ");
    scanf("%s", str);

    while(str[i]!='\0') {
       test[i]=str[i]; i++;
    }
}

If I were to print this it only gives me the ASCII code and not the letters associated with it. How would I take the ASCII code and turn it into letters? Or is there a better method for it

You want:

test[i] = orig[i] - 1;

If I were to print this it only gives me the ASCII code

That just means you are not printing it correctly. This should work:

printf("orig: %s, transformed: %s\n", orig, test);

In C, char is an integer type. There's no need to convert between a code and a letter: the letter is the code. For example, on ASCII systems 'a' == 97 .

In other words, you can simply do str[i]--; directly (assuming your platform uses ASCII).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM