Cho một chuỗi, chuyển đổi tất cả chữ hoa thành chữ thường và chữ thường thành chữ hoa. Ký tự đặc biệt giữ nguyên.
Ví dụ
Input - "Welcome To The Site!" Output - "wELCOME tO tHE sITE!"
Input - "HELLO" Output - "hello"
Phương pháp 1: Hàm thư viện
Sử dụng tolower(), toupper() từ <cctype>.
Phương pháp 2: Logic ASCII (Code dưới)
- 'A'-'Z': 65-90, 'a'-'z': 97-122
- Chữ thường → hoa: trừ 32
- Chữ hoa → thường: cộng 32
Ví dụ code C++
#include <iostream>
#include <string>
using namespace std;
void Convert_case(string &str) {
int len = str.length();
for (int i = 0; i < len; i++) {
if (str[i] >= 'a' && str[i] <= 'z')
str[i] = str[i] - 32;
else if (str[i] >= 'A' && str[i] <= 'Z')
str[i] = str[i] + 32;
}
}
int main() {
string str = "What's Your Name?";
cout << "Before: " << str;
Convert_case(str);
cout << "\nAfter: " << str;
return 0;
}
Kết quả
Before: What's Your Name? After: wHAT'S yOUR nAME?