c-使用ASCII将小写字母转换为大写字母



我正在尝试使用ASCII表将所有小写字母转换为大写字母!这很容易处理,我已经弄清楚了代码。问题是,如果单词之间有空格,那么程序只会更改第一个单词,在空格之后就不会打印任何内容。

示例
单词:Andreas Gives:Andreas
单词:TeSt123Ha给出:TeSt123Ha
但是
单词:你好45给予:你好
在空间之后,它什么也没印!

我知道ASCII表中的空格等于32,在我的代码中,我告诉程序,如果您正在读取的当前代码不在97和122之间,那么不要执行任何更改!

但它仍然不起作用!

char currentletter;
int i;
for (i=0; i<49; i++)    
{
    currentletter = str[i];
    if ((currentletter > 96) && (currentletter < 123))
    {
        char newletter;
        newletter = currentletter - 32;
        str[i] = newletter;
    }
    else
    {
        str[i] = currentletter;
    }
}
printf("%sn", str);

翻转第5个最低位应该会有所帮助。

每个小写字母等于32+大写字母。这意味着简单地翻转位置5处的位(从位置0处的最低有效位开始计数)将反转字母的大小写。https://web.stanford.edu/class/cs107/lab1/practice.html

char *str;
int str_size = sizeof(str);
for(int i=0; i<str_size;i++){
   if((str[i]>96) && (str[i]<123)) str[i] ^=0x20;
} 

您在其中一条注释中提到,您使用scanf("%s", str);来获取字符串。问题是%s一旦发现空白字符就会停止扫描。在您的情况下,它在看到空格字符时停止扫描。

如果要扫描一整行,请使用fgets()

fgets(str, sizeof(str), stdin);

这里需要注意的一点是,fgets也会将换行符扫描到字符串中。


您的代码可以简化为:

for (int i = 0; str[i] != ''; i++) // Loop until the NUL-terminator
{
    if ((str[i] >= 'a') && (str[i] <= 'z')) // If the current character is a lowercase alphabet
        str[i] = str[i] - ('a' - 'A');      // See the ASCII table to understand this:
                                            // http://www.asciitable.com/index/asciifull.gif
}
printf("%sn", str);

或者更简单的方法是使用ctype.h:中的tolower

#include <ctype.h>
for(int i = 0; str[i] != ''; i++) // Loop until the NUL-terminator
{
    str[i] = tolower(str[i]); // Convert each character to lowercase (It does nothing if the character is not an alphabet)
}
printf("%sn", str);

我尝试过使用STL和Lambda只是为了好玩:

string input = "";
getline(cin, input);
transform(input.begin(), input.end(), input.begin(), [](char c) { return (c > 96 && c < 123) ? c ^= 0x20 : c; });
copy(input.begin(), input.end(), ostream_iterator<char>(cout, " "));

我在Visual Studio 2019中使用c++17进行了编译和测试,并且没有进行详尽的测试!

相关内容

最新更新