เราได้รับสตริง งานคือการแปลงตัวอักษรพิมพ์ใหญ่เป็นพิมพ์เล็ก และพิมพ์เล็กเป็นพิมพ์ใหญ่ ส่วนตัวอักษรพิเศษคงเดิม
ตัวอย่าง
Input − "Welcome To The Site!" Output − "wELCOME tO tHE sITE!"
Input − "HELLO" Output − "hello"
แนวทางการแก้ปัญหา (ใช้ ASCII)
- A-Z: 65-90, a-z: 97-122 ความต่างคือ 32
- วนลูปแต่ละตัวอักษร:
- ถ้า 'a' ≤ c ≤ 'z': c = c - 32 (เป็นพิมพ์ใหญ่)
- ถ้า 'A' ≤ c ≤ 'Z': c = c + 32 (เป็นพิมพ์เล็ก)
- อีกวิธี: ใช้ฟังก์ชัน toupper(), tolower() จาก <cctype>
ตัวอย่างโค้ด C++
#include <iostream>
using namespace std;
void convertCase(string &str) {
for (char &c : str) {
if (c >= 'a' && c <= 'z')
c = c - 32;
else if (c >= 'A' && c <= 'Z')
c = c + 32;
}
}
int main() {
string str = "What's Your Name?";
cout << "Before: " << str << endl;
convertCase(str);
cout << "After: " << str;
return 0;
}
ผลลัพธ์
Before: What's Your Name? After: wHAT'S yOUR nAME?
บทความนี้สาธิตการสลับตัวพิมพ์ใหญ่/เล็กในสตริงโดยใช้การคำนวณค่า ASCII (บวก/ลบ 32) หรือใช้ฟังก์ชันมาตรฐาน toupper/tolower