C++中string类型字符串代码示例
//string 字符串使用示例
//string.cpp
#include <iostream>
#include <cstring>
using namespace std;
int main(void){
string s;//空字符串
cout<< s <<endl;//结果是啥也没有
string s1 = "hello";//定义并同时初始化
cout<< s1 <<endl;//结果:hello
//拷贝
string s2;
/*该拷贝过程形式简单,也比较安全,不用担心内存问题。
s1占用6个字符空间,s2仅仅是定义了,且是空字符,能够
放下s1吗?其实不用担心,因为string类型是在堆区开辟
空间维护字符串的,它将过程都封装起来了,若拷贝过程
中发现s2的内存不够用,他会完成动态的内存分配*/
s2 = s1;
cout<< s2 <<endl;//hello
//连接
string s3 = s1 + s2;
cout << s3 <<endl;//hellohello
//也可以和常量字符串连接
s3 = s1 + "world";
cout<< s3 <<endl;//hello world
//连接也可以用“+=”
s1 += "world";//s1=s1+"world";
cout<< s1 <<endl;//hello world
//比较
/*比较两字符串使用的较多的是判断两个字符串是否相等,
返回值是个逻辑值,若是真结果为1,若是假结果为0*/
cout<< (s1 == s2)<<endl;//0
cout<< (s1 != s2)<< endl;//1
//随机访问
/*随机访问是获取任意一个想要的字符*/
s1[0] = 'H';
s1[6] = 'W';
cout<< s1 <<endl;//Hello World
//获取字符串长度
/*获取字符串长度的函数是string的成员函数,可以
将string理解为结构体类型,里面包含和字符串相关
的成员函数。在求字符串长度时的结果是不包含字符
串结束标志“\n”的。以下两个成员函数等价,一般使
用第一个,由于字母少写起来简单。*/
cout<< s1.size() <<endl;//11
cout<<s1.length() <<endl;//11
//获取C风格的字符串
/*strlen()的参数为char* 类型的,使用成员函数c_str()
转换后再使用*/
cout<< strlen(s1.c_str())<< endl;//11
//交换
string s4= "hello";
string s5="world";
swap(s4,s5);
cout<< s4 <<endl;//world
cout<< s5 <<endl;//hello
return 0;
}