ความถี่ของตัวอักษร
นับจำนวนครั้งที่ตัวอักษรพิมพ์เล็กแต่ละตัวปรากฏ
ความถี่ของตัวอักษร คืออะไร?
ตารางความถี่จับคู่ตัวอักษรที่เป็นไปได้แต่ละตัวกับตัวนับ
ประเด็นสำคัญ
- เปิด compiler warning และแก้ทุกคำเตือน
- รู้ type และ lifetime ของทุกค่า
- ตรวจ input และขอบเขต array ให้ชัดเจน
ตัวอย่างโค้ด C และ C++
main.c
#include <stdio.h>
int main(void) {
const char *text = "banana"; int counts[26] = {0};
// Convert each lowercase letter to an array index.
for (; *text; ++text) ++counts[*text - 'a'];
for (int i = 0; i < 26; ++i) if (counts[i]) printf("%c=%d\n", 'a' + i, counts[i]);
}
a=3
b=1
n=2
C++
main.cpp
#include <array>
#include <iostream>
#include <string>
int main() {
std::string text = "banana"; std::array<int, 26> counts{};
// Convert each lowercase letter to an array index.
for (char character : text) ++counts[character - 'a'];
for (size_t i = 0; i < counts.size(); ++i) if (counts[i]) std::cout << char('a' + i) << '=' << counts[i] << '\n';
}
a=3
b=1
n=2
เปรียบเทียบ C และ C++
ใช้ระยะห่างของตัวอักษรจาก a เป็นดัชนีอาร์เรย์ และพิมพ์เฉพาะตัวนับที่ไม่เป็นศูนย์
C
C แสดง API แบบ procedural และรายละเอียด representation อย่างชัดเจน
C++
C++ รักษา low-level model และเพิ่ม type ที่ปลอดภัยกว่า
แบบฝึกหัด
รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา
- เพิ่ม input ผิดและค่าขอบเขต
- Compile ด้วย -Wall -Wextra -Wpedantic
- แยก declaration และ implementation
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
โจทย์ทั้งหมด