當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ std::memchr用法及代碼示例


C++提供了各種要使用的標準模板庫。其中一個是memchr()函數,它將在指定數量的字符中搜索字符的第一個匹配項。
模板

const void* memchr( const void* ptr, int ch, std::size_t count );
參數:
ptr: Pointer to the object to be searched for.
ch: Character to search for.
count: Number of character to be searched for.

返回值:
If the character is found, the memchr() function returns a pointer to 
the location of the character, otherwise returns null pointer.
// CPP program to illustrate memchr() 
#include <cstring> 
#include <iostream> 
  
using namespace std; 
  
int main() 
{ 
    char sr[] = "This is a sample"; 
    char ch = 's'; 
    int count = 13; 
  
    if (memchr(sr, ch, count)) 
        cout << ch << " is present in first "
             << count << " characters of \"" << sr << "\""; 
    else
        cout << ch << " is not present in first "
             << count << " characters of \"" << sr << "\""; 
  
    return 0; 
}

輸出:

s is present in first 13 characters of "This is a sample"

例:


// CPP program to illustrate memchr() 
#include <iostream> 
#include <cstring> 
  
int main() 
{ 
    char arr[] = { 'b', 'a', 'd', 'e', 'f', 'A', 'g' }; 
    char* pc = (char*)std::memchr(arr, 'g', sizeof arr); 
    if (pc != NULL) 
        std::cout << "search character found\n"; 
    else
        std::cout << "search character not found\n"; 
}

輸出:

search character found


相關用法


注:本文由純淨天空篩選整理自 std::memchr in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。