c++ - 这个数组转换是如何工作的(使用字符串将小写字母转换为大写字母)?

标签 c++ string uppercase lowercase

我让程序按预期工作,但谁能解释一下它是如何工作的?

#include <iostream>

using namespace std;

int main(void) {
    int exit;     
    string name;
    cin >> name;

    for (int i = 0; i < name.length(); i++) {
        // the line below is the one I don't understand 
        if ('a' <= name[i] && name[i] <= 'z') name[i] = char(((int)name[i]) - 32);
    }
    cout << name;
    cin >> exit;
    return 0;
 }

编辑:让我重新措辞:

我不明白的是字符串到数组的处理是如何工作的,如: 'a'<= name[i] .这到底比较了什么以及如何比较?

编辑2 感谢大家的快速回复,爱你们。我想通了。

最佳答案

这是一行:

 if('a'<=name[i] && name[i]<='z')name[i]=char(((int)name[i])-32);

segmentation :

 if( 'a'<=name[i] ) {
   if( name[i]<='z' ) {
     // name_int is a temporary, which the above code implicitly creates,
     // but doesn't give a name to:
     int name_int = name[i];
     name_int = name_int - 32;
     name[i] = char(name_int);
   }
 }

请注意 32 在您使用的字符编码中恰好等于 'a'-'A'

(技术上 name_int 应该是 int&& 或类似的东西,但没必要那么困惑。)

关于c++ - 这个数组转换是如何工作的(使用字符串将小写字母转换为大写字母)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14511727/

相关文章:

java - 在正则表达式中使用 Unicode 类别名称时出现 PatternSyntaxException

c++ - 在未格式化的输出中打印出来 C++

ruby-on-rails - Ruby:卡住数组中的字符串是否也应该单独卡住?

c - C 中的动态 3D 可变列字符数组操作

Java字符串分割删除空值

python - 打印十六进制值时如何让 Python 使用大写字母?

c++ - 在 C++ 中转换为大写

c++ - 模板化的多态回调是个好主意吗?

c++ - 推断程序是否要使用线程

c++ - 实现模板类接口(interface)