程序设计实习:7.4string类
string 类:
是一个模板类, 它的定义如下: typedef basic_stringstring; 使用string类要包含头文件string对象的初始化。
string s1("Hello"); // 一个参数的构造函数
string s2(8, ‘x’); // 两个参数的构造函数
string month = “March”;
不提供以字符和整数为参数的构造函数 错误的初始化方法:
string error1 = ‘c’; // 错
string error2(‘u’); // 错
string error3 = 22; // 错
string error4(8); // 错 可以将字符赋值给string对象
string s; s = ‘n’;
构造的string太长而无法表达:
会抛出length_error异常 string 对象的长度用成员函数 length()读取;
string s("hello"); cout << s.length() << endl; string 支持流读取运算符
string stringObject; cin >> stringObject; 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 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()); //s1.size(), s1字符数 cout << s2; //下标为3开始, s1.size()个字符 //如果字符串内没有足够字符, 则复制到字符串最后一个字符。
比较string:
输出 0 // hello == hello 1 // hello > hell -1 // hell < hello -1 // el < hell 1 // hello > hell
子串:
成员函数 substr() string s1("hello world"), s2; s2 = s1.substr(4,5); //下标4开始5个字符 cout << s2 << endl;
交换string:
成员函数 swap() string s1("hello world"), s2("really"); s1.swap(s2); cout << s1 << endl; cout << s2 << endl;
string的特性:
成员函数 capacity() 返回无需增加内存即可存放的字符 数 成员函数maximum_size() 返回string对象可存放的最大字符 数 成员函数length() 和size()相同 返回字符串的大小 /长度 成员函数empty() 返回string对象是否为 空 成员函数resize() 改变string对象的长度。
寻找string中的字符:
成员函数 find()
string s1("hello world"); s1.find("lo"); //在s1中从前向后查找 “lo” 第一次出现的地方 //如果找到, 返回 “lo”开始的位置, 即 l 所在的位置下标 //如果找不到, 返回 string::npos (string中定义的静态常量) 成员函数 rfind()
string s1("hello world"); s1.rfind("lo"); //在s1中从后向前查找 “lo” 第一次出现的地方 //如果找到, 返回 “lo”开始的位置, 即 l 所在的位置下标 //如果找不到, 返回 string::npos
成员函数 find_first_of()
string s1("hello world"); s1.find_first_of(“abcd"); //在s1中从前向后查找 “abcd” 中任何一个字符第一次出现的地方 //如果找到, 返回找到字母的位置; 如果找不到, 返回 string::npos 成员函数 find_last_of()
string s1("hello world"); s1.find_last_of(“abcd"); //在s1中查找 “abcd” 中任何一个字符最后一次出现的地方 //如果找到, 返回找到字母的位置; 如果找不到, 返回 string::npos
成员函数 find_first_not_of()
string s1("hello world"); s1.find_first_not_of(“abcd"); //在s1中从前向后查找不在 “abcd” 中的字母第一次出现的地方 //如果找到, 返回找到字母的位置; 如果找不到, 返回 string::npos 成员函数 find_last_not_of()
string s1("hello world"); s1.find_last_not_of(“abcd"); //在s1中从后向前查找不在 “abcd” 中的字母第一次出现的地方 //如果找到, 返回找到字母的位置; 如果找不到, 返回 string::npos
替换string中的字符:
在string中插入字符:
转换成C语言式char *字符串:
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.