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


C++ memchr()用法及代碼示例

C++ 中的memchr() 函數在指定字符數中搜索第一次出現的字符。

memchr()原型

const void* memchr( const void* ptr, int ch, size_t count );
void* memchr( void* ptr, int ch, size_t count );

memchr() 函數接受三個參數:ptr , chcount.

它首先將 ch 轉換為 unsigned char 並在 ptr 指向的對象的第一個 count 個字符中定位它的第一次出現。

它在<cstring> 頭文件中定義。

參數:

  • ptr:指向要搜索的對象的指針。
  • ch:要搜索的字符。
  • count :要搜索的字符數。

返回:

如果找到字符,memchr() 函數返回一個指向字符位置的指針,否則返回空指針。

示例:memchr() 函數的工作原理

#include <cstring>
#include <iostream>

using namespace std;

int main()
{
    char ptr[] = "This is a random string";
    char ch = 'r';
    int count = 15;
    
    if (memchr(ptr,ch, count))
        cout << ch << " is present in first " << count << " characters of \"" << ptr << "\"";
    else
        cout << ch << " is not present in first " << count << " characters of \"" << ptr << "\"";

    return 0;
}

運行程序時,輸出將是:

r is present in first 15 characters of "This is a random string"

相關用法


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