在编程代码中将小写转换为大写为什么我们使用(str [i]> = 97 && str [i] <= 122)?

Ver*_*ium 1 c++ string lowercase toupper

所以这是我用来转换小写的程序,大写你可以告诉我为什么我们使用这个东西?[(str [i]> = 97 && str [i] <= 122)]在下面的代码部分?

#include <iostream.h>
#include <conio.h>
#include <string.h>
void main()
{
    clrscr();
    char str[20];
    int i;
    cout << "Enter the String (Enter First Name) : ";
    cin >> str;
    for (i = 0; i <= strlen(str); i++) {
        if (str[i] >= 97 && str[i] <= 122) //Why do we use this???
        {
            str[i] = str[i] - 32;
        }
    }
    cout << "\nThe String in Uppercase = " << str;
    getch();
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*l R 7

这部分代码编写得非常糟糕:

if(str[i]>=97 && str[i]<=122)
{
 str[i]=str[i]-32;
}
Run Code Online (Sandbox Code Playgroud)

它将更加便携,更具可读性:

if(str[i]>='a' && str[i]<='z')
{
 str[i]=str[i]-'a'+'A';
}
Run Code Online (Sandbox Code Playgroud)

或者更好的是,使用标准的C库宏/函数(来自<ctype.h>):

if(islower(str[i]))
{
 str[i]=toupper((unsigned char)str[i]);
}
Run Code Online (Sandbox Code Playgroud)

或者甚至更好,你可以完全跳过测试并写:

str[i]=toupper((unsigned char)str[i]);
Run Code Online (Sandbox Code Playgroud)

(因为toupper如果它不是小写字母,将返回char不变).