C++ std::string
1. STL中的 string 类型支持类似java中的直接进行字符串相加,但是不支持相减
#include <iostream> #include <string> using namespace std; int main() { string str = "Hello World"; str += " I am comming!"; cout << str << endl; //只能+=,不能-= int a = 123456; str = to_string(a); //c++11引入的,编译时需要加上-std=c++11 cout << a << endl; printf("str=%s\n", str.c_str()); //string和char*转换 return 0; } $ g++ std_string.cpp -o pp -std=c++11 $ ./pp Hello World I am comming! 123456 123456
2. 常用demo
(1) 字符串拼接
#include <iostream> #include <fstream> #include <string> using namespace std; int std_string_test(void) { int tid = 1122; //int tid = gettid(); //无法调用成功 std::string str = "/proc/" + std::to_string(tid) + "/comm"; cout << str << endl; // /proc/1122/comm cout << str.c_str() << endl; // /proc/1122/comm } int main() { std_string_test(); return 0; }
(2)字符串比较
#include <iostream> #include <string> int main () { std::string str1 ("green apple"); std::string str2 ("red apple"); if (str1.compare(str2) != 0) std::cout << str1 << " is not " << str2 << '\n'; if (str1.compare(6, 5,"apple") == 0) //只比较str1中的apple字段 std::cout << "still, " << str1 << " is an apple\n"; if (str2.compare(str2.size()-5, 5, "apple") == 0) //只取str2的最后5个字符进行比较 std::cout << "and " << str2 << " is also an apple\n"; if (str1.compare(6, 5, str2, 4, 5) == 0) //str从第6个字符开始和str2的从第4个字符开始,比较5个字符 std::cout << "therefore, both are apples\n"; return 0; } /* $ g++ std_string.cpp -o pp $ ./pp green apple is not red apple still, green apple is an apple and red apple is also an apple therefore, both are apples */
(3) 字符串拼接
std::string path_name = "/proc/" + std::to_string(getpid()) + "/task/" + std::to_string(gettid()) + "/status";
优秀博文:
std::string简介及其使用:https://www.cnblogs.com/leaves1024/p/10270753.html
【C++ STL String】常用操作: https://www.jianshu.com/p/90584f4404d2
std:string: https://blog.csdn.net/L_insting/article/details/110149869
posted on 2021-06-28 20:59 Hello-World3 阅读(212) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!