std::strstr_C++中文网

C++ 参考手册

在 str 所指的字节字符串中寻找字节字符串 target 的首次出现。不比较空终止字符。

参数

str - 指向要检验的空终止字节字符串的指针
target - 指向要查找的空终止字节字符串的指针

返回值

指向 str 中寻获子串的首个字符的指针,或若找不到该字符则为 NULL 。若 target 指向空字符串,则返回 str 。

示例

#include <iostream>
#include <cstring>
 
int main()
{
    const char *str = "Try not. Do, or do not. There is no try.";
    const char *target = "not";
    const char *result = str;
 
    while ((result = std::strstr(result, target)) != NULL) {
        std::cout << "Found '" << target 
                  << "' starting at '" << result << "'\n";
 
        // 自增 result ,否则会找到同一位置的目标
        ++result;
    }   
}

输出:

Found 'not' starting at 'not. Do, or do not. There is no try.'
Found 'not' starting at 'not. There is no try.'

参阅