C语言字符串查找知识点搬运

1. 

头文件:#include <string.h>

strchr() 用来查找某字符在字符串中首次出现的位置,其原型为:
    char * strchr (const char *str, int c);

【参数】str 为要查找的字符串,c 为要查找的字符。

strchr() 将会找出 str 字符串中第一次出现的字符 c 的地址,然后将该地址返回。

注意:字符串 str 的结束标志 NUL 也会被纳入检索范围,所以 str 的组后一个字符也可以被定位。

【返回值】如果找到指定的字符则返回该字符所在地址,否则返回 NULL。

返回的地址是字符串在内存中随机分配的地址再加上你所搜索的字符在字符串位置。设字符在字符串中首次出现的位置为 i,那么返回的地址可以理解为 str + i。

提示:如果希望查找某字符在字符串中最后一次出现的位置,可以使用 strrchr() 函数。

【实例】查找字符5首次出现的位置。

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. int main(){
  5.     char *s "0123456789012345678901234567890";
  6.     char *p;
  7.     p strchr(s'5');
  8. printf("%ld\n", s);
  9.     printf("%ld\n", p);
  10. system("pause");
  11.     return 0;
  12. }

输出结果:
12016464
12016469

2.  https://zhidao.baidu.com/question/265212596486109045.html

//#include "stdafx.h"//If the vc++6.0, with this line.
#include "stdio.h"
#include "string.h"
int  main( void ){
     char  a[50]= "1234567890" ,b[10]= "345" ,*pt;
     if (pt= strstr (a,b))
         printf ( "From %d of the beginning.\n" ,pt-a);
     else  printf ( "Not find \'%s\'.\n" ,b);
     return  0;
}

3. 

extern int strcmp(const char *s1,const char *s2);



当s1<s2时,返回为负数;
当s1==s2时,返回值= 0;
当s1>s2时,返回正数。
即:两个 字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇'\0'为止。如:
"A"<"B" "a">"A" "computer">"compare"
特别注意:strcmp(const char *s1,const char * s2)这里面只能比较字符串,即可用于比较两个字符串常量,或比较数组和字符串常量,不能比较数字等其他形式的参数。

猜你喜欢

转载自blog.csdn.net/zhang_fei_fresh/article/details/76474245