請注意,我並不是問在C++中將小寫字母轉換爲大寫字母的方法是什麼,而是我想知道下面代碼(Upper1和Upper2)中的哪兩種方法更好比另一個更重要,這是什麼原因,編程是明智的。在C++中將小寫字母轉換爲大寫字母
#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);
}
您指出了一些優點,謝謝! – Cache