字符串數組各元素長度不一,sizeof 計算的是整個數組佔用的總字節數(含填充對齊),而非元素個數。
char* str[] = {"hello", "world", "this", "is", "test"};
// 錯誤:sizeof(str) / sizeof(str[0]) 在指針退化時失效
// 正確(僅在數組定義作用域內):
size_t count = sizeof(str) / sizeof(str[0]); // 5
關鍵:str[0] 必須是佔用空間最大的元素(或任意元素,因指針數組每元素固定為指針大小)。對於 char str[][MAX_LEN] 二維數組,sizeof(str[0]) 為固定行長。
統計數組中每個不同字符串出現次數,類似整型數組去重計數。
#include
#include
#include
#include
// 現代 C++ 推薦:unordered_map 一行搞定
std::unordered_map freq;
for (const auto& s : strArray) freq[s]++;
// 教學版:標誌數組法 (O(n²),適合小數據量/無 STL 環境)
void countFrequency(const std::vector& arr) {
int n = arr.size();
std::vector flag(n, 0); // 0=未統計, 1=已統計
for (int i = 0; i < n; ++i) {
if (flag[i]) continue;
int cnt = 1;
for (int j = i + 1; j < n; ++j) {
if (!flag[j] && arr[j] == arr[i]) {
cnt++;
flag[j] = 1; // 標記已統計
}
}
std::cout << arr[i] << ": " << cnt << '\n';
}
}
| 需求 | 推薦容器/算法 | 代碼片段 |
|---|---|---|
| 動態字符串集合 | std::vector | vec.push_back(s); |
| 頻次統計 | std::unordered_map | ++freq[s]; |
| 去重 | std::unordered_set | set.insert(s); |
| 排序 | std::sort(vec.begin(), vec.end()) | sort(v.begin(), v.end()); |
| 查找 | std::binary_search / set.count | binary_search(v.begin(), v.end(), s); |
| 分詞/分割 | std::stringstream / boost::split | boost::split(tokens, s, is_any_of(" ")); |
❌ 用char*數組手動管理內存 → 易洩漏、越界、釋放錯誤
❌ 用sizeof計算指針數組長度(指針退化後失效)
❌ 手寫 O(n²) 統計邏輯(除非嵌入式無 STL)
✅ 優先用std::string+std::vector+unordered_map
✅ 字符串視圖std::string_view(C++17) 避免拷貝
✅ 大數據量用std::sort+ 線性掃描統計 (O(n log n))
CSDN 字符串操作總結: https://blog.csdn.net/wangfengwf/article/details/11496141
字符串數組操作的核心是選對容器。
現代 C++ 標準庫已提供完整、高效、安全的解決方案。
手寫底層邏輯僅用於學習原理或極受限環境。