c++知识细节-c++标准库-string类型
简介
char str[100] = "I Love China"
c语言中用法
string s1 = "I Love China"
c++用法,可与char数组互转
Tips:需要#include <string>
和using namespace std
,仅管iostream中已间接引用到了string,但还是建议直接#include <string>
全部内容.
定义和初始化string对象
string s1;
//默认初始化,s1为空串string s2 = "I Love China";
//将字符串"I Love China"拷贝到了s2代表的一段内存中,拷贝时不包含末尾的’\0’string s3("I Love China");
//同s2string s4=s2
//s4复制s2,内存地址不同string s5(5,'a');
//初始化为连续的5个a字符,不推荐,会产生临时对象
string对象上的常用操作
- empty(): 判断是否为空,返回布尔值
string s1;
cout << s1.empty();
- size()/length(): 返回字节数量,代表该字符串长度,unsigned int
string s1 = "我爱中国";
cout << s1.size(); //8
cout << s1.length(); //8
- s[n]: 返回s中的第n个字符 ,n为0到size()-1,不要越界
string s = "I Love China";
cout << s[3]; //'o'
- s1 + s2: 字符串连接,返回一个新的string对象
string s1 = "I Love ";
string s2= "Chine";
string s3 = s1 + s2;
cout << s3; //"I Love China"
- s1 == s2: 判断两个字符串是否相等,大小写敏感
string s = "I Love China";
cout << s[3]; //'o'
- s.c_str(): 返回字符串s的内容指针,指向s对象的内容区,以’\0’结尾,返回一个指针常量.为了与c语言兼容,可以把string对象转换为c语言中的字符串样式
string s = "abc";
const char * p = s.c_str(); //"abc"
- 读写string对象
string s;
cin >> s; //直接从键盘输入,空格无效
- 字面值和string相加
string s = "abc";
string s2 = s + "def"; //"abcdef",涉及到隐式类型转换
string s3 = "abc" + "def" + s; //不允许,两个字符串不能挨着,因为不知道转成什么类型
- 范围for对string的应用,string可以看做是一个字符序列
string s = "I Love Chine";
for (auto c : s) //变量类型自动推断,char
{
cout << c;
}