strstr
来自cppreference.com
| 定义于头文件 <string.h>
|
||
| char *strstr( const char* str, const char* substr ); |
||
查找 substr 所指的空终止字节字符串在 str 所指的空终止字节字符串中的首次出现。不比较空终止字符。
若 str 或 substr 不是指向空终止字节字符串的指针,则行为未定义。
参数
| str | - | 指向要检验的空终止字节字符串的指针 |
| substr | - | 指向要查找的空终止字节字符串的指针 |
返回值
指向于 str 中找到的子串首字符的指针,或若找不到该子串则为空指针。若 substr 指向空字符串,则返回 str 。
示例
运行此代码
#include <string.h> #include <stdio.h> void find_str(char const* str, char const* substr) { char* pos = strstr(str, substr); if(pos) { printf("found the string '%s' in '%s' at position: %ld\n", substr, str, pos - str); } else { printf("the string '%s' was not found in '%s'\n", substr, str); } } int main(void) { char* str = "one two three"; find_str(str, "two"); find_str(str, ""); find_str(str, "nine"); find_str(str, "n"); return 0; }
输出:
found the string 'two' in 'one two three' at position: 4 found the string '' in 'one two three' at position: 0 the string 'nine' was not found in 'one two three' found the string 'n' in 'one two three' at position: 1