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
直接上代码吧,
值得一说的事情是,代码中的注释,’\t’,在用vim编辑时,tab键不代表’\t’,需要用\t来表示。
相应的在C++中string对应的函数是find_first_of与find_last_of
直接贴代码,
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; }
相关文章推荐
- 网络编程(0)--multicast
- 小小菜之Cocos2d-x游戏开发旅程——项目实例:飞机大战(4)
- POJ - 3468 A Simple Problem with Integers(线段树)
- iOS开发5-NSURLSession实现Http通信
- 2015.10.20
- Codeforces Round #326 (Div. 1) - C. Duff in the Army 树上倍增算法
- 函数基础
- Liunx常用命令
- CNN初步-1
- ubuntu配置网络安装
- 记首届国赛
- Codevs P3641 上帝选人
- 黑马程序员----反射机制
- poj 1753 BFS+位运算(set优化)
- 用Java解析XML,并转换为json格式(2)
- 素数的求解(c语言)
- ubuntu14.0.4网络图标不见了
- Codeforces Round #326 (Div. 2) B
- [转载]面试IT公司的经验
- 编程思想之多线程与多进程(1)——以操作系统的角度述说线程与进程