|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
1、string概念
1. string是STL的字符串类型,通常用来表示字符串。传统的字符串通常是用字符指针char* 或 字符数组模拟字符串。
2. string是一个类,char*是指向字符的指针, string封装了char*,并管理这个char*,是char*的一个容器。
3. string不用考虑内存释放和越界,string自动管理这块内存。
4. string提供了一系列的字符串操作函数。
2、string的构造函数
1. 默认构造
s1 = string(); 构造一个空串s1;
2. 拷贝构造函数
string(const string &str); 构造一个与str一样的string;
3. 带参的构造函数
string(const char *s); 用字符串s初始化string;
string(int n, char c); 用n个字符c初始化。
- string s1 = "abcdef";
- string s2("123456");
- string s3 = s2; // 通过拷贝构造函数初始化
- string s4(5, 'a');
- cout << s1 << endl << s2 << endl << s3 << endl << s4 << endl;
复制代码
3、string的存取和遍历
- string s1;
- for (int i = 0; i < s1.length(); i++)
- {
- cin >> s1[i] ; // []不会抛出异常, 直接中断, s[i]可以当左值
- cout << s1.at(i); // at(i)发生异常时,可以抛出异常。
- }
- cout << endl;
- // 2、迭代器
- for (string::iterator it = s1.begin(); it != s1.end(); it++)
- {
- cout << *it << " ";
- }
- cout << endl;
复制代码
4、字符指针和string的相互转换
- string s5 = "ABC123"; // char* ==> string
- char * p = (char *)s5.c_str(); // string ==> char*
- cout << p << endl;
- // string字符串拷贝到字符数组
- char buf[128] = { 0 };
- //s1.copy(buf1, 3, 0); // 从第0个字符开始复制,复制3个字符到buf1下,VS2015下不安全
- strcpy_s(buf, s5.c_str());
- s1._Copy_s(buf, 128, 3, 0);
- cout << buf << endl;
复制代码
5、字符串的连接
- string s6;
- s6 = s1 + s2; // 重载了+运算符
- s6.append(s5);
- cout << s6 << endl;
复制代码
6、字符串查找和替换
- int index = s7.find("abc", 0); //从位置0开始查找
- cout << "index:" << index << endl;
- // 查找ab每次出现位置的下标
- while (index != string::npos)
- {
- cout << "index:" << index << " ";
- index++;
- index = s7.find("abc", index); //find()函数未找到返回-1,即string::npos
- }
- cout << endl;
- // 把abc替换为ABC
- index = s7.find("abc", 0);
- while (index != string::npos)
- {
- s7.replace(index, 3, "ABC"); // 从index位置起删除3个字符,然后在插入“ABC”
- index++;
- index = s7.find("abc", index); //find()函数未找到返回-1,即string::npos
- }
- cout << s7 << endl;
复制代码
7、字符串区间删除和插入
- string s8 = "hello1 hello2 hello3";
- string::iterator it = find(s8.begin(), s8.end(), 'l'); //#include "algorithm"
- if (it != s8.end())
- {
- s8.erase(it);
- }
- cout << "s8:" << s8 << endl;
- s8.erase(s8.begin(), s8.end()-6); //部分和全部删除
- cout << s8 << endl;
-
- s8.insert(0, "AAA"); // 在零位置插入“AAA”
- s8.insert(s8.length(), "BBB"); // 尾部插入"BBB"
- cout << s8 << endl;
复制代码
8、大小写转换
包含于#include "algorithm"
- string s9 = "AAAbbb";
- transform(s9.begin(), s9.end(), s9.begin(), toupper);
- cout << s9 << endl;
- transform(s9.begin(), s9.end(), s9.begin(), tolower);
- cout << s9 << endl;
复制代码 |
|