程序设计与算法三八周笔记string

string 类

string 类是模板类: typedef basic_string string;

使用string类要包含头文件<string>

string对象的初始化:

– string s1("Hello");

– string month = "March";

– string s2(8,’x’); string 类 //s2为8个x

错误的初始化方法:

– string error1 = ‘c’; // 错

– string error2(‘u’); // 错

– string error3 = 22; // 错

– string error4(8); // 错

可以将字符赋值给string对象

– string s;

扫描二维码关注公众号,回复: 2576879 查看本文章

s = ‘n’;

string类程序样例

string 类

string 对象的长度用成员函数 length()读取

string s("hello");

cout<<s.length()<<endl;

string支持流读取运算符

string s;

cin>>s;

string 支持getline函数

string s;

getline(cin ,s);

string 的赋值

• 用 = 赋值

– string s1("cat"), s2;

– s2 = s1;

• 用 assign 成员函数复制

– string s1("cat"), s3;

– s3.assign(s1);

• 用 assign 成员函数部分复制

– string s1("catpig"), s3;

– s3.assign(s1, 1, 3); – //从s1 中下标为1的字符开始复制3个字符给s3

 • 单个字符复制

s2[5] = s1[3] = ‘a’;

• 逐个访问string对象中的字符

string s1("Hello");

for(int i=0;i<s1.length();i++)

   cout<<s1.at(i)<<endl;

成员函数at会做范围检查,如果超出范围,会抛出out_of_range异常,而下标运算符[]不做范围检查

string 的连接 

用 + 运算符连接字符串

string s1("good "), s2("morning! ");

s1 += s2;

cout<<s1;

用成员函数append连接字符串

string  s1("good"),s2("morning!");

s1.append(s2);

cout<<s1;

s2.append(s1,3,s1.size());

子串 substr

成员函数 substr

string s1("hello world"), s2;

s2 = s1.substr(4,5); // 下标4开始5个字符

cout << s2 << endl;

输出: o wor

交换stringswap

成员函数 swap

string s1("hello world"), s2("really");

s1.swap(s2);

cout << s1 << endl;

cout << s2 << endl;

输出: really hello world

猜你喜欢

转载自blog.csdn.net/qq_31647835/article/details/81383680