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

ฟังก์ชัน strspn() ในภาษา C


ฟังก์ชัน strspn() ใช้สำหรับคำนวณความยาวของส่วนต้น (substring) ของสตริงแรกที่ประกอบด้วยตัวอักษรที่มีอยู่ในสตริงที่สองทั้งหมด ฟังก์ชันนี้คืนค่าความยาวของส่วนนั้น

ไวยากรณ์

size_t strspn(const char *string1, const char *string2);

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

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

int main() {
    const char s1[] = "Helloworld!";
    const char s2[] = "Hello";
    int length = strspn(s1, s2);
    printf("The length of string : %d", length);
    return 0;
}

ผลลัพธ์

The length of string : 5

คำอธิบาย: ในตัวอย่าง สตริง s1 เริ่มต้นด้วย "Hello" ซึ่งตัวอักษรทุกตัวอยู่ใน s2 ("Hello") แต่ตัวถัดไปคือ 'w' ซึ่งไม่อยู่ใน s2 ดังนั้นฟังก์ชันคืนค่า 5 (ความยาวของ "Hello")