diff --git a/md/0004.md b/md/0004.md index 24d8b09..f093902 100644 --- a/md/0004.md +++ b/md/0004.md @@ -1,5 +1,6 @@ -โจทย์ข้อนี้สามารถแก้ได้โดยการนำสตริงที่ได้มาจากข้อมูลนำเข้ามาตรวจสอบว่ามีตัวพิมพ์ใหญ่หรือไม่และมีตัวพิมพ์เล็กหรือไม่ ทั้งนี้วิธีการหลักๆในการเขียนโค้ดสำหรับข้อนี้คือการใช้ function ที่ให้มากับภาษา (จาก cctype ใน C++ เป็นต้น) ที่เรียกกันว่า standard library เราจะใช้ function ```isupper(c)``` และ ```islower(c)``` จาก header cctype เพื่อตรวจสอบว่า ```c``` เป็นตัวพิมพ์ใหญ่หรือไม่และตรวจสอบว่า ```c``` เป็นตัวพิมพ์เล็กหรือไม่ดังนี้ +โจทย์ข้อนี้สามารถแก้ได้โดยการนำสตริงที่ได้มาจากข้อมูลนำเข้ามาตรวจสอบว่ามีตัวพิมพ์ใหญ่หรือไม่และมีตัวพิมพ์เล็กหรือไม่ ทั้งนี้วิธีการหลักๆในการเขียนโค้ดสำหรับข้อนี้คือการใช้ function ที่ให้มากับภาษา (จาก cctype ใน C++ เป็นต้น) ที่เรียกกันว่า standard library เราจะใช้ function ```isupper(c)``` และ ```islower(c)``` จาก header cctype สำหรับ C++ หรือ ctype.h สำหรับ C เพื่อตรวจสอบว่า ```c``` เป็นตัวพิมพ์ใหญ่หรือไม่และตรวจสอบว่า ```c``` เป็นตัวพิมพ์เล็กหรือไม่ดังนี้ +C++ : ```cpp #include #include @@ -19,3 +20,56 @@ int main() { } ``` +C : +```c +#include +#include +#include + +int main(){ + bool has_upper = false; // เก็บว่า s มีตัวพิมพ์ใหญ่หรือไม่ + bool has_lower = false; // เก็บว่า s มีตัวพิมพ์เล็กหรือไม่ + char s[10001]; + scanf("%s", s); + for(int i=0; s[i]!='\0'; i++){ + if(isupper(s[i])) has_upper = true; + else has_lower = true; + } + if(has_lower && has_upper) printf("Mix"); + else if(has_upper) printf("All Capital Letter"); + else printf("All Small Letter"); +} +``` + +C with memory allocation: +```c +#include +#include +#include +#include + +int main(){ + bool has_upper = false; // เก็บว่า s มีตัวพิมพ์ใหญ่หรือไม่ + bool has_lower = false; // เก็บว่า s มีตัวพิมพ์เล็กหรือไม่ + char *s = malloc(10001); // จัดหน่วยความจำสำหรับสตริง 10000 ตัวอักษร + if (s == NULL) { + printf("Memory allocation failed!\n"); + return 1; + } + + // รับสตริงจากผู้ใช้ โดยกำหนดขนาดสูงสุด + if (scanf("%10000s", s) != 1) { + printf("Error reading input!\n"); + free(s); + return 1; + } + for(int i=0; s[i]!='\0'; i++){ + if(isupper(s[i])) has_upper = true; + else has_lower = true; + } + free(s); // ใช้ free ในการล้าง memory ที่ s ใช้มา + if(has_lower && has_upper) printf("Mix"); + else if(has_upper) printf("All Capital Letter"); + else printf("All Small Letter"); +} +```