Chuỗi trong C và C++
C lưu văn bản trong mảng char kết thúc bằng ký tự ẩn '\0', còn C++ bọc văn bản trong std::string, tự quản lý bộ nhớ cho bạn.
Chuỗi trong C và C++ là gì?
C lưu văn bản trong mảng char kết thúc bằng ký tự ẩn '\0', còn C++ bọc văn bản trong std::string, tự quản lý bộ nhớ cho bạn.
So sánh mảng ký tự của C với std::string của C++: độ dài, nối, so sánh và tìm kiếm.
Điểm quan trọng
- Luôn bật compiler warning và xử lý mọi cảnh báo.
- Hiểu rõ type và lifetime của từng giá trị.
- Kiểm tra input và giới hạn mảng rõ ràng.
Code ví dụ bằng C và C++
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
/* A C string is a char array that ends with '\0'. */
char name[32] = "Ada";
printf("%s has %zu letters\n", name, strlen(name));
/* strcat appends; the array must have room for the result. */
strcat(name, " Lovelace");
printf("%s\n", name);
/* strcmp returns 0 when two strings are equal. */
printf("equal: %d\n", strcmp("cat", "cat") == 0);
/* Walk the characters until the terminating '\0'. */
char upper[32];
size_t i = 0;
for (; name[i] != '\0'; i++) {
upper[i] = (char)toupper((unsigned char)name[i]);
}
upper[i] = '\0';
printf("%s\n", upper);
/* strstr finds a substring and returns a pointer to it, or NULL. */
printf("contains \"love\": %s\n", strstr("lovelace", "love") ? "yes" : "no");
return 0;
}
Ada has 3 letters
Ada Lovelace
equal: 1
ADA LOVELACE
contains "love": yes
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
int main() {
// std::string manages its own memory and grows as needed.
std::string name = "Ada";
std::cout << name << " has " << name.size() << " letters\n";
name += " Lovelace";
std::cout << name << '\n';
// == compares the contents of two strings.
std::cout << "equal: " << (std::string("cat") == "cat") << '\n';
std::string upper = name;
std::transform(upper.begin(), upper.end(), upper.begin(),
[](unsigned char c) { return static_cast<char>(std::toupper(c)); });
std::cout << upper << '\n';
// find returns std::string::npos when the text is missing.
std::string word = "lovelace";
std::cout << "contains \"love\": " << (word.find("love") != std::string::npos ? "yes" : "no") << '\n';
std::cout << "first name: " << name.substr(0, 3) << '\n';
}
Ada has 3 letters
Ada Lovelace
equal: 1
ADA LOVELACE
contains "love": yes
first name: Ada
So sánh C và C++
Trong C, strlen, strcat, strcmp và strstr làm việc trên mảng thô và bạn phải đảm bảo mảng đủ lớn. std::string có size(), +=, ==, find() và substr(), tự mở rộng nên tránh được tràn bộ đệm.
C dùng API thủ tục nhỏ gọn và thể hiện chi tiết biểu diễn rõ ràng.
C++ giữ mô hình low-level nhưng bổ sung type thư viện và abstraction an toàn hơn.
Bài tập mở rộng
Chạy cả hai phiên bản rồi thay đổi để quan sát khác biệt về bảo đảm của từng ngôn ngữ.
- Thêm input sai và boundary value.
- Biên dịch với -Wall -Wextra -Wpedantic.
- Tách declaration dùng lại vào header và implementation file.
Luyện tập với thử thách
Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.
- Count Uppercase Letters Count the capital letters in a text. Dễ
- Chữ Viết Tắt Từ Họ Tên Tạo chữ viết tắt in hoa từ một họ tên đầy đủ. Dễ
- Replace Spaces With Dashes Turn spaces into dashes to make a URL-style slug. Dễ