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   Hello-World3  阅读(212)  评论(0编辑  收藏  举报

编辑推荐:
· 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框架的用法!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示