不使用 toUpper()、toLower()、length()、at() 或 [] -- 转换 "Hey!!在那里!"到"嘿!嘭!
Without using toUpper(), toLower(), length(), at() or [] -- Convert "Hey!! THERE!" to "hEy!! tHeRe!"
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]
另外,字符串总是以