不使用 toUpper()、toLower()、length()、at() 或 [] -- 转换 "Hey!!在那里!"到"嘿!嘭!

Without using toUpper(), toLower(), length(), at() or [] -- Convert "Hey!! THERE!" to "hEy!! tHeRe!"

本文关键字:Hey 转换 在那里 toUpper toLower length at      更新时间:2023-10-16
void crazyCaps(string& str){
size_t i = 0;
size_t strLength = str.length();  // this line violates the rule as mentioned in the title
while (i < strLength) {
    if (i % 2 == 0) {
        if (str[i] >= 'A' && str[i] <= 'Z')   // this line violates the rule as mentioned in the title
            str[i] += 32;
    }
    else {
        if (str[i] >= 'a' && str[i] <= 'z') 
            str[i] -= 32;
    }
    i++;
}
我的输入:"嘿!!"在那里!"

我的输出:"hEy!!那儿!"

我可以在不使用toUpper()和toLower()函数的情况下将字符转换为大写和小写。但是,我仍然使用length()和[]。所以我的问题是,你如何将"嘿!!"到"嘿!!"tHeRe!",无需使用length()或[]以及toUpper()或toLower()。

str[i]等价于*(str + i)。编译器内部将str[i]转换为*(str + i)
这意味着,str[i] = *(str + i) = i[str]

另外,字符串总是以(空字符)结尾。使用这两个事实,您可以构造如下内容:

int i = 0
while(*(str + i) != '') {
    //change the case by adding or subtracting 32
    i++;
}
编辑:这里的字符串是指普通的C字符串,而不是std::string