当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。