Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน strchr() ใน C++ และการประยุกต์ใช้

ฟังก์ชัน strchr() คืออะไร?

ฟังก์ชัน strchr() เป็นฟังก์ชันในตัวของ C++ STL ประกาศอยู่ใน header <cstring> ใช้ค้นหา ครั้งแรก (first occurrence) ของตัวอักษร (character) ในสตริง (C-style string / null-terminated string) ฟังก์ชันนี้คืนค่า pointer ชี้ไปยังตำแหน่งที่พบตัวอักษรครั้งแรก

หากไม่พบตัวอักษรในสตริง จะคืนค่า nullptr (null pointer)

รูปแบบไวยากรณ์ (Syntax)

char* strchr(const char* str, int charac);

หมายเหตุ: parameter ที่ 2 เป็น int แต่จะถูกแปลงเป็น unsigned char ภายใน

พารามิเตอร์

  • str - C-style string ที่ต้องการค้นหา (null-terminated)
  • charac - ตัวอักษรที่ต้องการค้นหา (รหัส ASCII)

ค่าที่ส่งคืน (Return Value)

  • Pointer ชี้ไปยังตัวอักษรครั้งแรกที่พบในสตริง
  • nullptr หากไม่พบตัวอักษรนั้นในสตริง

ตัวอย่างการใช้งาน

ตัวอย่างที่ 1: ตรวจสอบว่าตัวอักษรมีอยู่ในสตริงหรือไม่

#include <iostream>
#include <cstring>
using namespace std;

int main() {
    char str[] = "Tutorials Point";
    char ch_1 = 'b', ch_2 = 'T';
    
    if (strchr(str, ch_1) != nullptr) {
        cout << ch_1 << " is present in string" << endl;
    } else {
        cout << ch_1 << " is not present in string" << endl;
    }
    
    if (strchr(str, ch_2) != nullptr) {
        cout << ch_2 << " is present in string" << endl;
    } else {
        cout << ch_2 << " is not present in string" << endl;
    }
    
    return 0;
}

ผลลัพธ์

b is not present in string
T is present in string

ตัวอย่างที่ 2: ใช้ร่วมกับ strcat()

#include <iostream>
#include <cstring>
using namespace std;

int main() {
    char str[] = "Tutorials Point";
    char str_2[] = " is a learning portal";
    char ch_1 = 'b', ch_2 = 'T';
    
    if (strchr(str, ch_1) != nullptr) {
        cout << ch_1 << " is present in string" << endl;
    } else {
        cout << ch_1 << " is not present in string" << endl;
    }
    
    if (strchr(str, ch_2) != nullptr) {
        cout << ch_2 << " is present in string" << endl;
        strcat(str, str_2);  // ต่อสตริงหากพบ 'T'
        cout << "String after concatenation is: " << str;
    } else {
        cout << ch_2 << " is not present in string" << endl;
    }
    
    return 0;
}

ผลลัพธ์

b is not present in string
T is present in string
String after concatenation is: Tutorials Point is a learning portal

ฟังก์ชันที่เกี่ยวข้อง

ฟังก์ชันคำอธิบาย
strrchr()ค้นหา ครั้งสุดท้าย (last occurrence) ของตัวอักษร
strstr()ค้นหา substring (สตริงย่อย)
strpbrk()ค้นหาตัวอักษรใดตัวหนึ่งจากชุดที่กำหนด

สรุป

strchr() เป็นฟังก์ชันพื้นฐานสำหรับการค้นหาตัวอักษรใน C-style string ใช้ร่วมกับ pointer arithmetic เพื่อหาตำแหน่ง (index) หรือตัดสตริงได้ ฉบับ C++ แบบ modern ควรใช้ std::string::find() แทนเพื่อความปลอดภัยและสะดวกกว่า