C++ string类

一.初始化

string string1;
string string2="hello world";
string string3("hello world"); string string4(10,'h');

 

二.对象的比较

可以用 <、<=、==、!=、>=、> 运算符比较 string 对象。按照字典序比较字符串的大小。

还可以使用+运算符拼接字符串

string string2="hello ";
string string3("world");
string string4=string2+string3;//hello world

 

三.求 string 对象的子串

substr 成员函数可以用于求子串 (n, m),函数原型如下:

string substr(int n = 0, int m = string::npos) const;

调用时,如果省略 m 或 m 超过了字符串的长度,则求出来的子串就是从下标 n 开始一直到字符串结束的部分。

string string1="hello world";
string string2=string1.substr(1,7);//ello wo
string string3=string1.substr(1);//ello world

四.string和int的互相转化

1.int转换成string

    string str=to_string(-12);//"-12"
    string str1=to_string(12);//"12"
    string str2=to_string(-1+2);//"1"

2.string转换成int

    string str=to_string(-12);//"-12"
    //先转化为char*型,而后再转化为int
    int a=atoi(str.c_str());//-12
原文地址:https://www.cnblogs.com/AntonioSu/p/11957499.html