首先介绍一些查找字符的函数
1、strrchr
头文件:#include <string.h>
strrchr() 函数用于查找某字符在字符串中最后一次出现的位置,其原型为:
char * strrchr(const char *str, int c);
【参数】str 为要查找的字符串,c 为要查找的字符。
strrchr() 将会找出 str 字符串中最后一次出现的字符 c 的地址,然后将该地址返回。
注意:字符串 str 的结束标志 NUL 也会被纳入检索范围,所以 str 的组后一个字符也可以被定位。
【返回值】如果找到就返回该字符最后一次出现的位置,否则返回 NULL。
返回的地址是字符串在内存中随机分配的地址再加上你所搜索的字符在字符串位置。设字符在字符串中首次出现的位置为 i,那么返回的地址可以理解为 str + i。
2、strchr
头文件:#include <string.h>
strchr() 用来查找某字符在字符串中首次出现的位置,其原型为:
char * strchr (const char *str, int c);
【参数】str 为要查找的字符串,c 为要查找的字符。
strchr() 将会找出 str 字符串中第一次出现的字符 c 的地址,然后将该地址返回。
注意:字符串 str 的结束标志 NUL 也会被纳入检索范围,所以 str 的组后一个字符也可以被定位。
【返回值】如果找到指定的字符则返回该字符所在地址,否则返回 NULL。
返回的地址是字符串在内存中随机分配的地址再加上你所搜索的字符在字符串位置。设字符在字符串中首次出现的位置为 i,那么返回的地址可以理解为 str + i。
提示:如果希望查找某字符在字符串中最后一次出现的位置,可以使用 strrchr() 函数。
3、strstr
头文件:#include <string.h>
strstr()函数用来检索子串在字符串中首次出现的位置,其原型为:
char *strstr( char *str, char * substr );
【参数说明】str为要检索的字符串,substr为要检索的子串。
【返回值】返回字符串str中第一次出现子串substr的地址;如果没有检索到子串,则返回NULL。
例子1:
#include<string.h>
#include<stdio.h>
char *find_file_name(const char *name)
{
char *name_start = NULL;
int sep = '/';
if (NULL == name) {
printf("the path name is NULL\n");
return NULL;
}
name_start = strrchr(name, sep);
return (NULL == name_start)?name:(name_start + 1);
}
int main(void)
{
char string[15],mypath[66]={0};
char*ptr,c='r';
char filepath[]="/home/linux_c/hello.c";
strcpy(string,"Thisisastring");
ptr=strchr(string,c);
if(ptr)
printf("The character %c is at position:%d\n",c,ptr-string+1);
else
printf("The character was not found\n");
printf("\n\n filename is %s \n\n",find_file_name(filepath));
return 0;
}
例子2:
//windows下路径测试
#include "stdio.h"
#include "string.h"
int main(void){
char fn[30],*p;
char pathname[80]="e:\\1\\2\\abc.dat";
//上句假设以某种方式获得的全文件名在pathname中,"..."中只是举例
strcpy(fn,(p=strrchr(pathname,'\\')) ? p+1 : pathname);
//上句函数第2实参这样写以防止文件在当前目录下时因p=NULL而出错
printf("%s\n",fn);//打出来看看
return 0;
}
参考:http://c.biancheng.net/cpp/u/string_h/