C 標準庫 – string.h之memchr使用

zhangrxiang發表於2019-05-12

memchr

  • Locate character in block of memory,Searches within the first num bytes of the block of memory pointed by ptr for the first occurrence of ch (interpreted as an unsigned char), and returns a pointer to it.
  • 在引數 ptr 所指向的字串的前 count 個位元組中搜尋第一次出現字元 ch(一個無符號字元)的位置。
  • Both ch and each of the bytes checked on the the ptr array are interpreted as unsigned char for the comparison.
  • 在 ptr 所指向物件的首 count 個字元(每個都轉譯成 unsigned char )中尋找 ch (在如同以 (unsigned char)ch 轉換到 unsigned char 後)的首次出現。
  • 若訪問出現於被搜尋的陣列結尾後,則行為未定義。
  • 若 ptr 為空指標則行為未定義。
  • 此函式表現如同它按順序讀取字元,並立即於找到匹配的字元時停止:

    • 若 ptr 所指向的字元陣列小於 count ,但在陣列中找到匹配,則行為良好定義。
void* memchr( const void* ptr, int ch, size_t count );

Parameters

ptr

  • Pointer to the block of memory where the search is performed.
  • 指向要檢驗的物件的指標

ch

  • ch to be located. The ch is passed as an int, but the function performs a byte per byte search using the unsigned char conversion of this ch.
  • 要搜尋的字元
  • 以 int 形式傳遞的值,但是函式在每次位元組搜尋時是使用該值的無符號字元形式。

count

  • Number of bytes to be analyzed,size_t is an unsigned integral type.
  • 要檢驗的最大字元數

Return Value

  • A pointer to the first occurrence of ch in the block of memory pointed by ptr.If the ch is not found, the function returns a null pointer.
  • 指向字元位置的指標,或若找不到該字元則為 NULL 。
  • 該函式返回一個指向匹配位元組的指標,如果在給定的記憶體區域未出現字元,則返回 NULL。

Example

//
// Created by zhangrongxiang on 2018/2/8 14:10
// File memchr
//

//C 庫函式 void *memchr(const void *str, int c, size_t n)
// 在引數 str 所指向的字串的前 n 個位元組中搜尋第一次出現字元 c(一個無符號字元)的位置。

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

int main() {
    //字串
    char str[] = "I am your God";
    //陣列
    int arr[] = {10, 20, 30, 40, 50, 60, 70, 80, 90};
    char *position = (char *) memchr(str, `y`, strlen(str));
    if (position) {
        printf("%s
", position);//your God
        printf("%d
", (int) (position - str));//5
        printf("%c
", str[position - str]); //y
    } else {
        printf("null
");
    }
    int *pInt = (int *) memchr(arr, 50, sizeof(arr));
    printf("%d
", *pInt);//50
    printf("%c
", *pInt);//2
    printf("%c
", (unsigned char) 50); //2
    printf("%c
", (char) 50); //2
    printf("%c
", 50);//2
    printf("%c
", (unsigned char) 51); // 3

    return 0;
}

文章參考

轉載註明出處

相關文章