试图转换大写字符在C小写,而无需使用功能 [英] Trying to convert uppercase char to lowercase in C without using a function

查看:227
本文介绍了试图转换大写字符在C小写,而无需使用功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个char元素从的char * ARGV []数组转换大写字母为小写,而无需使用功能。我想补充32到ASCII整数。

I am trying to convert a char element from an char *argv[] array to lowercase from uppercase without using a function. I want to add 32 to the ascii integer.

当我尝试将变量作为参数传递,它会显示整数总和,而不是新的小写字符。相反,它会显示以下的输出:

When I try to pass the variable as an argument, it will show the integer sum, but not the new lowercase character. Instead it shows the following output:

letter h, 104
tolower: 136, �

code:

int i = 0;
for(i = 0; argv[1][i] != '\0'; i++) {
    char letter = argv[1][i];

    printf("letter %c, %i\n", letter, letter);
    char tolower = argv[1][i];
    int lowercase = tolower + 32;

    printf("tolower: %i, %c\n", lowercase, lowercase);
}

为什么打印?烧焦?

Why is it printing a "?" char?

推荐答案

我不会点的问题,其他的回答者做,我将展示一个巧妙的方法来进行交换的上下。为字母,小写和大写字母之间的差别是在ASCII code中的第5位。因此要设置字母小写,你需要设置该位:

I will not point the problems that other answerers did, I will show a neat trick to perform the swap upper-lower. For the letters, the difference between the lower case and the upper case letters is the bit 5 in the ascii code. So to set the letter lowercase you need to set this bit:

lower = 0x20 | letter;

有关大写复位位:

upper = (~0x20) & letter;

和交换可以使用XOR的情况:

And to swap the case you can use XOR:

swapped = 0x20 ^ letter;

这里的好东西,你不用担心,检查信件是否已经你需要的情况下。

The good thing here that you don't have to worry and check whether or not the letter is already the case you need.

这篇关于试图转换大写字符在C小写,而无需使用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆