简体   繁体   English

通过减去c语言中的ASCII码来更改char

[英]changing char by subtracting its ASCII code in c language

I am doing some string workshop for my c learning. 我正在为我的c学习做一些弦乐工作坊。 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". 有一个问题,您要求用户输入“ bob”,并且代码要降低其ASCII码,使其变为“ 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. 如果要打印此文件,它只会给我ASCII码,而不是与之关联的字母。 How would I take the ASCII code and turn it into letters? 我该如何将ASCII码转换成字母? 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 如果我要打印此文件,它只会给我ASCII码

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. 在C中, char是整数类型。 There's no need to convert between a code and a letter: the letter is the code. 无需在代码和字母之间进行转换:字母就是代码。 For example, on ASCII systems 'a' == 97 . 例如,在ASCII系统上'a' == 97

In other words, you can simply do str[i]--; 换句话说,您可以简单地执行str[i]--; directly (assuming your platform uses ASCII). 直接(假设您的平台使用ASCII)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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