28/07/2023
28/07/2023
#include <iostream>
#include <string>
#include <cctype>
// Hàm chuẩn hóa xâu họ tên
std::string normalizeName(const std::string& s) {
std::string result = s;
bool isSpace = true; // Biến kiểm tra xem có dấu cách thừa không
// Chuẩn hóa chữ cái đầu mỗi từ là in hoa, còn lại là in thường
for (size_t i = 0; i < result.length(); ++i) {
if (isSpace && std::islower(result[i])) {
result[i] = std::toupper(result[i]);
} else {
result[i] = std::tolower(result[i]);
}
isSpace = (result[i] == ' ');
}
// Loại bỏ dấu cách thừa
size_t pos = result.find(" "); // Tìm vị trí có 2 dấu cách liên tiếp
while (pos != std::string::npos) {
result.erase(pos, 1); // Xóa dấu cách thừa
pos = result.find(" ", pos); // Tìm tiếp vị trí có 2 dấu cách liên tiếp (nếu còn)
}
// Loại bỏ dấu cách ở đầu và cuối chuỗi
if (!result.empty() && result.front() == ' ') {
result.erase(result.begin());
}
if (!result.empty() && result.back() == ' ') {
result.pop_back();
}
return result;
}
int main() {
std::string input;
std::cout << "Nhap xau ho ten: ";
std::getline(std::cin, input);
std::string output = normalizeName(input);
std::cout << "Xau sau khi chuan hoa: " << output << std::endl;
return 0;
}
Nếu bạn muốn hỏi bài tập
Các câu hỏi của bạn luôn được giải đáp dưới 10 phút
CÂU HỎI LIÊN QUAN
Top thành viên trả lời