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

How to convert std::string to lower case in C++?


ในส่วนนี้ เราจะดูวิธีแปลงตัวอักษรทั้งหมดของ C++ string ให้เป็นตัวพิมพ์เล็ก (lowercase) เพื่อทำสิ่งนี้เราต้องใช้ transform function ฟังก์ชัน transform นี้อยู่ใน algorithm library

Transform function รับ beginning pointer ของ string และ ending pointer ของ string มันยังรับ beginning ของ string เพื่อเก็บผลลัพธ์ แล้ว argument ที่สี่คือ ::tolower ซึ่งช่วยแปลง string เป็น lowercase string เราสามารถใช้วิธีเดียวกันนี้ถ้าต้องการแปลง string ให้เป็น uppercase ได้

ตัวอย่างโค้ด

#include <iostream>
#include <algorithm>
using namespace std;
int main() {
    string my_str = "Hello WORLD";
    cout << "Main string: " << my_str << endl;
    transform(my_str.begin(), my_str.end(), my_str.begin(), ::tolower);
    cout << "Converted String: " << my_str;
}

ผลลัพธ์

Main string: Hello WORLD
Converted String: hello world