C字符串函数
C字符串函数
1 strstr()
C标准库string.h中的函数。
1.1 声明
char *strstr(const char *haystack, const char *needle)
在字符串 haystack
中查找第一次出现字符串 needle
的位置,不包含终止符 \0
。未找到则返回null。
1.2 示例
const char haystack[20] = "RUNOOB";
const char needle[10] = "NOOB";
char *ret;
ret = strstr(haystack, needle);
printf("子字符串是: %s\n", ret);
输出结果:NOOB。
2 LC - strstr()的实现(28)
2.1 注意事项
strlen()
的返回值是无符号整型。无符号整型相减可能溢出。 下面的写法是错误的,strlen()
相减可能为负:
int strStr(char* haystack, char* needle) {
unsigned int h_len = strlen(haystack), n_len = strlen(needle);
//"unsigned int"错误,因为for循环中相减,可能为负!
for (int i = 0; i < h_len - n_len + 1; i++) {
...
}
}
只需声明为int型,或强制转换为int型即可:
int h_len = strlen(haystack), n_len = strlen(needle);
This post is licensed under CC BY 4.0 by the author.