2022年7月9日星期六

C strcspn

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

IBM的說明 

Computes the length of the initial portion of the string pointed to by string1 that contains no characters from the string pointed to by string2.

我的理解是:計算string2中的所有字母 在string1中出現的經過幾次比對次數才發現string2中的字母,從string1的起始開始字元開始比對,依序比對string2中的所有字元,如下圖示意。如果發現沒有相符字元,累計計數並繼續搜尋,直到發現相符字母才停止搜尋,並回傳比對的次數。

與之前的strspn的邏輯有點顛倒,未發先string2中的字元時,需要累加次數,如下圖


程式碼直接做比較快理解,在string1中搜尋string2中的字元。

程式碼

  1. #include <stdio.h>
  2. #include <string.h>
  3. int main(void)
  4. {
  5. char *string1 = "Hello world";
  6. char *string2 = "wor";
  7. int index = strcspn(string1, string2);
  8.  
  9. printf( "index:%d\n", index);
  10. }

執行結果

可以發現執行結果回傳4,因為發現'o'的位置剛好是比對四次後的地方。


沒有留言:

發佈留言

打賞按讚