C++ STL : std::string
来源:互联网 发布:画皮Q传源码 编辑:程序博客网 时间:2024/05/08 03:37
练习下C++ STL中std::string类的常用方法,方便以后查阅。
如有不正确的地方,请读者及时指正,欢迎转载,谢谢!
#include <assert.h>#include <string>//测试std::stringinline void testString(){//构造string,编译器会对下面语句进行优化,不同编译器调用过程可能不一样,VC下调用情况如下:std::string str1("hello Jim, welcome to china.");//直接初始化,调用构造函数std::string str2(str1);//直接初始化,调用拷贝构造函数std::string str3 = "hello Jim, welcome to china.";//拷贝初始化,调用构造函数std::string str4 = str3;//拷贝初始化,调用拷贝构造函数std::string str5 = std::string("hello Jim, welcome to china."); //同str3//字符串查找//查找字符串Jim第一次出现的位置std::size_t pos = str1.find("Jim");assert(pos == 6);//查找字符','第一次出现的位置pos = str1.find(',');assert(pos == 9);//反向查找字符串Jim第一次出现的位置pos = str1.rfind("Jim");assert(pos == 6);//查找,:.中的某个字符第一次出现的位置pos = str1.find_first_of(",:.");assert(pos == 9);//查找,:.中的某个字符最后一次出现的位置pos = str1.find_last_of(",:.");assert(pos == 27);//字符串操作//substr截取子串开始直到Jim,左闭右开std::string frontstr = str1.substr(0, str1.find("Jim"));assert(frontstr == "hello ");//substr截取子串Jim开始直到最后,左闭右开std::string backstr = str1.substr(str1.find("Jim"), str1.size());assert(backstr == "Jim, welcome to china.");//重新拼接字符串str1 = frontstr.append(backstr);assert(str1=="hello Jim, welcome to china.");//替换字符串Jim为Jackstr1.replace(str1.find("Jim"), strlen("Jim"), "Jack");//删除字符串hello和后面的空格str1.erase(str1.find("hello "), strlen("hello "));//交互teststr和teststr2的值str1.swap(str2);assert(str1=="hello Jim, welcome to china.");assert(str2=="Jack, welcome to china.");//比较字符串str1和str2的大小,大于返回1,小于返回-1,==返回0int compare = str1.compare(str2);assert(compare == 1);//小写字母的ascii码大于大写字母//字符串插入insertstr1.insert(str1.find("Jim")+strlen("Jim"), " Green");assert(str1 == "hello Jim Green, welcome to china.");return;}
0 0
- C++/STL std::string 的用法
- C++ STL : std::string
- std::string and stl 算法
- std::string and stl 算法
- 如何將std::string轉成大寫(小寫)? (C/C++) (STL) (C)
- 如何將std::string轉成大寫(小寫)? (C/C++) (STL) (C)
- stl 中std::string 的方法
- STL std::string 字符全局替换
- 入门计划->学用stl std::map<std::string, int>
- C/C++ std::string 切词
- 【语言-C++】STL std::list的使用
- C++STL之string
- [C++]STL string类
- C++STL之string
- C++STL之string
- C++STL之string
- c++STL之string
- C++STL之string
- CodeForces 551E GukiZ and GukiZiana (分块)
- 反射Demo代码
- 购买服务器的个人经验
- iOS系统架构
- JAVA的StringBuffer类
- C++ STL : std::string
- 工作流管理系统开发之六 表单权限与流程的权限控制
- 第四章 课后作业4
- 安装PHP报You don't have permission to access /test.php on this server.怎C样解决
- Linux 编译 OpenCV 出现 ‘cv::imread(std::__cxx11:: 错误的解决方案
- 关于struct dirent 中d_name成员在某些系统中为1的问题。
- Log4j日志
- ROS中配置主从机需注意的几点
- Android内存基础——Java内存管理机制