Skip to main content
 首页 » 编程设计

C++ std::string

2022年07月19日166thcjp

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 
*/

优秀博文:

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


本文参考链接:https://www.cnblogs.com/hellokitty2/p/14946291.html