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

ฟังก์ชันค้นหาสตริง (String Searching Functions) ในภาษา C


คำอธิบาย

ไลบรารี C มีฟังก์ชันค้นหาสตริงหลายตัวใน :

char *strchr(const char *s, int c)หาตำแหน่งแรกของตัวอักษร c ใน s
char *strrchr(const char *s, int c)หาตำแหน่งสุดท้ายของตัวอักษร c ใน s
char *strpbrk(const char *s1, const char *s2)หาตำแหน่งแรกใน s1 ที่มีตัวอักษรใดตัวหนึ่งจาก s2
size_t strspn(const char *s1, const char *s2)นับจำนวนตัวอักษรต้นของ s1 ที่อยู่ใน s2
size_t strcspn(const char *s1, const char *s2)นับจำนวนตัวอักษรต้นของ s1 ที่ ไม่อยู่ ใน s2
char *strtok(char *s1, const char *s2)แยก s1 เป็นโทเคน คั่นด้วยตัวอักษรจาก s2
char *strtok_r(char *s1, const char *s2, char **saveptr)Thread-safe version ของ strtok

ตัวอย่าง 1: strchr()

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

void main() {
    char *str1 = "Hello";
    char *ans = strchr(str1, 'l');
    printf("%s\n", ans); // Output: llo
}

ans ชี้ไปที่ str1 + 2 (ตัว 'l' ตัวแรก)

ตัวอย่าง 2: strpbrk()

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

void main() {
    char *str1 = "Hello";
    char *ans = strpbrk(str1, "aeiou");
    printf("%s\n", ans); // Output: ello
}

ans ชี้ไปที่ str1 + 1 (ตัว 'e' ตัวแรกที่เป็นสระ)