Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การแปลง C++ String เป็นตัวพิมพ์ใหญ่

ตัวอย่างโค้ด (C-style String)

#include <iostream>
#include <cstring>
using namespace std;

int main() {
    char s[30] = "This_is_string";
    for (int i = 0; i <= strlen(s); i++) {
        if (s[i] >= 97 && s[i] <= 122)  // 'a' to 'z'
            s[i] = s[i] - 32;
    }
    cout << "The String in Uppercase = " << s;
    return 0;
}

ผลลัพธ์

The String in Uppercase = THIS_IS_STRING

วิธี C++ Modern (std::string)

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

int main() {
    std::string s = "This_is_string";
    
    // transform กับ ::toupper
    std::transform(s.begin(), s.end(), s.begin(), 
                   [](unsigned char c){ return std::toupper(c); });
    
    std::cout << "Uppercase: " << s;
    return 0;
}

ผลลัพธ์

Uppercase: THIS_IS_STRING

คำแนะนำ

  • ใช้ std::toupper จาก <cctype> รองรับ Locale
  • Cast เป็น unsigned char ก่อนส่งให้ toupper (ป้องกัน UB กับค่าลบ)
  • std::transform ทำงานกับ Iterator เหมาะกับ STL Containers