请注意,我不是在问在 C++ 中将小写字母转换为大写字母的方法是什么,而是我想知道下面代码(Upper1 和 Upper2)中这两种方法中的哪一种比另一种更好,原因是什么,编程明智。
#include <string>
#include <iostream>
#include <locale> //Upper2 requires this module
using namespace std;
void Upper1(string &inputStr);
void Upper2(string &inputStr);
int main(){
string test1 = "ABcdefgHIjklmno3434dfsdf3434PQRStuvwxyz";
string test2 = "ABcdefgHIjklmnoPQRStuvwxyz";
Upper1(test1);
cout << endl << endl << "test1 (Upper1): ";
for (int i = 0; i < test1.length(); i++){
cout << test1[i] << " ";
}
Upper2(test2);
cout << endl << endl << "test2 (Upper2): ";
for (int i = 0; i < test2.length(); i++){
cout << test2[i] << " ";
}
return 0;
}
void Upper1(string &test1){
for (int i = 0; i < 27; i++){
if (test1[i] > 96 && test1[i] <123){ //convert only those of lowercase letters
test1[i] = (char)(test1[i]-(char)32);
}
}
}
void Upper2(string &test2){
locale loc;
for (size_t i=0; i<test2.length(); ++i)
test2[i] = toupper(test2[i],loc);
}