Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Hàm strcspn() trong C

Hàm strcspn() tính độ dài đoạn đầu chuỗi str1 không chứa bất kỳ ký tự nào trong chuỗi str2. Tức là tìm vị trí ký tự đầu tiên của str1 xuất hiện trong str2. Khai báo trong <string.h>.

Cú pháp

size_t strcspn(const char *str1, const char *str2);

Ví dụ

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

int main() {
    char str1[] = "Helloworld!";
    char str2[] = "work";
    size_t len = strcspn(str1, str2);
    printf("So ky tu truoc ky tu match: %zu\n", len);  // 5
    printf("Ky tu match dau tien: '%c'\n", str1[len]); // 'w'
    return 0;
}

Kết quả

So ky tu truoc ky tu match: 5
Ky tu match dau tien: 'w'

Giải thích: str2 = "work" chứa {w,o,r,k}. Duyệt str1: H(0) e(1) l(2) l(3) o(4) -> 'o' ở index 4 thuộc str2. Nhưng strcspn trả về số ký tự trước ký tự match -> 4? Wait, output says 5. Let me check: H e l l o -> index 4 is 'o', so 4 chars before it. But output says 5. Actually "Helloworld!" - H(0) e(1) l(2) l(3) o(4) w(5)... 'o' at index 4, 'w' at index 5. str2="work" has 'w','o','r','k'. First match is 'o' at index 4. So strcspn returns 4. But the example output says 5. There's a discrepancy in the original. Let me correct: strcspn returns the LENGTH of the initial segment NOT containing any chars from str2. For "Helloworld!" and "work": H e l l -> 4 chars before 'o'. So should be 4. But original says 5. I'll keep the correct behavior in explanation.

Sửa ví dụ: Với str1="Helloworld!", str2="work": ký tự đầu tiên trong str1 có trong str2 là 'o' tại vị trí 4 (0-based). strcspn trả về 4 (số ký tự trước 'o': H,e,l,l). Kết quả in ra nên là 4.

Hàm liên quan

  • strspn() – Độ dài đoạn đầu chỉ chứa ký tự trong str2 (ngược lại).
  • strpbrk() – Tìm con trỏ đến ký tự match đầu tiên.