您的位置:首页 > 其它

strrchr与strchr函数 find_first_of与find_last_of

2015-10-20 22:52 369 查看
这两个是字符串的查找函数:

char buf[1024] = “Hello world\t12”;

char sep1 = ‘\t’, sep2 = ’ ‘;

char *p;

p = strrchr(buf, sep1);

表示在字符串buf中反向查找sep1字符,若找到,则返回指向该字符的指针;若没有找到,则返回NULL

p = strrchr(buf, sep2);

表示在字符串buf中正向查找sep2字符,若找到,则返回指向该字符的指针;若没有找到,则返回NULL

直接上代码吧,

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
//#define N 10240
#define LEN 10240

int main()
{
char buf[LEN] = "test string\t12"; // the problem of char '\t'
char sep = '\t';

char *p;
char buf1[LEN], buf2[LEN];
p = strrchr(buf, sep);
*p = '\0';
int i = 0;
p ++;

int num = atoi(p);
while(*p)
{
buf1[i ++] = *p;
p ++;
}
p = buf;
i = 0;
while(*p)
{
buf2[i++] = *p;
p ++;
}
printf("The string is %s\n", buf2);
printf("The number is %d\n", num);

sep = ' ';
char buf3[LEN], buf4[LEN];
p = strchr(buf2, sep);
if(p == NULL)
{
printf("The return is NULL\n");
exit(-1);
}
*p = '\0';
p ++;
i = 0;
while(*p)
{
buf3[i ++] = *p;
p ++;
}
p = buf2;
i = 0;
while(*p)
{
buf4[i ++] = *p;
p ++;
}
printf("The first string is %s,\tThe second string is %s\n", buf4, buf3);

return 0;
}


值得一说的事情是,代码中的注释,’\t’,在用vim编辑时,tab键不代表’\t’,需要用\t来表示。

相应的在C++中string对应的函数是find_first_of与find_last_of

直接贴代码,

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
//#define N 10240
#define LEN 10240

int main()
{
char buf[LEN] = "teststring\t12";
char sep = '\t';
std::string str = (std::string)buf;
std::string str1, str2;
std::string::size_type ind = str.find_last_of(sep);
if(ind != std::string::npos)
{
std::cout << "The test" << std::endl;
str1 = str.substr(0, ind);
str2 = str.substr(ind + 1, str.size());
}
std::cout << "The ORG is " << (std::string)buf << std::endl;
std::cout << "str1 : " << str1 << std::endl;
std::cout << "str2 : " << str2 << std::endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: