Chuyển đổi chữ hoa ↔ thường bằng cách cộng/trừ 32 (khoảng cách ASCII giữa 'A' và 'a').
Chuyển thành CHỮ HOA
#include <stdio.h>
#include <string.h>
#include <ctype.h> // Cách tốt hơn
// Cách 1: Toán học ASCII (Chỉ dùng cho ASCII)
void toUpperAscii(char* str) {
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] = str[i] - 32; // hoặc str[i] &= ~0x20
}
}
}
// Cách 2: Dùng ctype.h (Khuyến nghị - portable, locale-aware)
void toUpperCtype(char* str) {
for (int i = 0; str[i] != '\0'; i++) {
str[i] = toupper((unsigned char)str[i]);
}
}
int main() {
char s[100];
printf("Nhập chuỗi: ");
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0'; // Xóa newline
toUpperCtype(s);
printf("Chữ HOA: %s\n", s);
return 0;
}
Kết quả
Nhập chuỗi: hello world! Chữ HOA: HELLO WORLD!
Chuyển thành CHỮ THƯỜNG
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void toLowerCtype(char* str) {
for (int i = 0; str[i] != '\0'; i++) {
str[i] = tolower((unsigned char)str[i]);
}
}
int main() {
char s[100];
printf("Nhập chuỗi: ");
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0';
toLowerCtype(s);
printf("Chữ thường: %s\n", s);
return 0;
}
Kết quả
Nhập chuỗi: HELLO WORLD Chữ thường: hello world
C++ - std::string + Algorithm (Hiện đại)
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
int main() {
std::string s = "Hello World!";
// In-place transform
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c) { return std::toupper(c); });
std::cout << "Upper: " << s << '\n'; // HELLO WORLD!
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c) { return std::tolower(c); });
std::cout << "Lower: " << s << '\n'; // hello world!
// Tạo bản copy
std::string upper = s;
std::transform(upper.begin(), upper.end(), upper.begin(),
[](unsigned char c) { return std::toupper(c); });
return 0;
}
C++20: std::format + ranges (Tương lai)
// C++26 dự kiến có std::to_upper, std::to_lower cho string // Hiện tại có thể dùng: #includeauto upper_view = s | std::views::transform([](char c) { return std::toupper(c); });
Tại sao cast (unsigned char)?
toupper/tolower nhận int nhưng yêu cầu giá trị trong khoảng unsigned char hoặc EOF. Trên hệ thống char signed, ký tự > 127 thành âm → UB. Cast (unsigned char) đảm bảo an toàn.
So sánh cách tiếp cận
| Phương pháp | Ưu điểm | Nhược điểm |
|---|---|---|
| ASCII math (±32) | Nhanh, không thư viện | Chỉ ASCII, không locale |
| ctype.h (toupper/tolower) | Portable, locale-aware | Chậm hơn chút, cần cast |
| C++ transform + lambda | STL style, an toàn, reusable | Verbose hơn |