Devdit
 

ค้นหา string ใน array ภาษาซี ด้วยคำสั่ง strcmp

0.9K

ค้นหา string ใน array ภาษาซี บทความนี้สอนเขียนโค้ดค้นหา string ในตัวแปรชนิด array ด้วยภาษา C โดยใช้หลักการวนลูป for จากข้อมูลในตัวแปร array ทั้งหมด และเปรียบเทียบค่าด้วยคำสั่ง if สามารถเขียนโปรแกรมได้ดังนี้

 

ตัวอย่าง ค้นหา string ใน array ภาษาซี ด้วยคำสั่ง strcmp

#include <stdio.h>
#include <stdbool.h>
#include <string.h>

int main() {
    const char *product[2];
    product[0] = "book";
    product[1] =  "pen";
    
    int size = sizeof product / sizeof product[0];
    bool found = false;
    char find[10] = "pen";

    for( int i=0; i<=size; i++ ) {
      if( strcmp(product[i], find) == 0 ) {
        found = true;
        continue;
      }
    }

    if( found ) {
      printf("พบ string ใน array");
    } else {
      printf("ไม่พบ string ใน array");
    }
  
    return 0;
}

ผลลัพธ์

พบ string ใน array

คำอธิบาย

ค้นหา string ใน array ภาษาซี ด้วยคำสั่ง strcmp มีรายละเอียดดังนี้

1. ตัวแปร array เก็บในตัวแปรชื่อ product ชนิด char array แบบ pointer

2. ตัวแปร size เก็บจำนวนข้อมูลใน array product เพื่อใช้ในการหาจุดสิ้นสุดในการวนลูป for

3. ตัวแปร found ชนิด boolean เก็บค่า true กรณีพบ string ใน array และ false กรณีไม่พบ

4. ตัวแปร find เก็บ string ที่ต้องการค้นหาใน array

5. ใช้ for วนลูปข้อมูลจากตัวแปร array product และใช้คำสั่ง if( strcmp(product[i], find) == 0 ) เพื่อหาค้น string ในตัวแปร find กับ array product

6. กรณีคำสั่ง strcmp คืนค่าเป็น 0 แปลว่าพบให้ตัวแปร found = true และใช้คำสั่ง continue เพื่อออกจากลูป for

7. กรณีตัวแปร found เป็น true ให้ทำงานใน if และถ้าเป็น false ให้ทำงานใน else

แก้ไข 1 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ