文章目录
在使用 string 类时,必须包含 #include 头文件以及 using namespace std ;
一、string类的迭代器、auto和范围for
迭代器
//迭代器
string s1("hello word");
string::iterator it = s1.begin();
while (it != s1.end())
{
cout << *it << endl;
++it;
}
cout << endl;
auto关键字
- 早期C/C++中auto的含义是:使用auto修饰的变量,是具有自动存储器的局部变量,后来这个不重要了。C++11中,标准委员会变废为宝赋予了auto全新的含义即:auto不再是一个存储类型指示符,而是作为一个新的类型指示符来指示编译器,auto声明的变量必须由编译器在编译时期推导而得。
- 用auto声明指针类型时,用auto和auto*没有任何区别,但用auto声明引用类型时则必须加&。
- 当在同一行声明多个变量时,这些变量必须是相同的类型,否则编译器将会报错,因为编译器实际只对第一个类型进行推导,然后用推导出来的类型定义其他变量。
- auto不能作为函数的参数,可以做返回值,但是建议谨慎使用。
- auto不能直接用来声明数组。
#include<iostream>
using namespace std;
int func1()
{
return 10;
}
// 不能做参数
void func2(auto a)
{}
// 可以做返回值,但是建议谨慎使用
auto func3()
{
return 3;
}
int main()
{
int a = 10;
auto b = a;
auto c = 'a';
auto d = func1();
auto e; // 编译报错:rror C3531: “e”: 类型包含“auto”的符号必须具有初始值设定项
cout << typeid(b).name() << endl;
cout << typeid(c).name() << endl;
cout << typeid(d).name() << endl;
int x = 10;
auto y = &x;
auto* z = &x;
auto& m = x;
cout << typeid(x).name() << endl;
cout << typeid(y).name() << endl;
cout << typeid(z).name() << endl;
auto aa = 1, bb = 2;
// 编译报错:error C3538: 在声明符列表中,“auto”必须始终推导为同一类型
auto cc = 3, dd = 4.0;
// 编译报错:error C3318: “auto []”: 数组不能具有其中包含“auto”的元素类型
auto array[] = { 4, 5, 6 };
return 0;
}
#include<iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
std::map<std::string, std::string> dict = { { "apple", "苹果" },{ "orange", "橙子" }, {"pear","梨"} };
// auto的用武之地
//std::map<std::string, std::string>::iterator it = dict.begin();
auto it = dict.begin();
while (it != dict.end())
{
cout << it->first << ":" << it->second << endl;
++it;
}
return 0;
}
范围for
- 对于一个有范围的集合而言,由程序员来说明循环的范围是多余的,有时候还会容易犯错误。因此C++11中引入了基于范围的for循环。for循环后的括号由冒号“ :”分为两部分:第一部分是范围内用于迭代的变量,第二部分则表示被迭代的范围,自动迭代,自动取数据,自动判断结束。
- 范围for可以作用到数组和容器对象上进行遍历。
- 范围for的底层很简单,容器遍历实际就是替换为迭代器,这个从汇编层也可以看到。
#include<iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
int array[] = { 1, 2, 3, 4, 5 };
// C++98的遍历
for (int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
{
array[i] *= 2;
}
for (int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
{
cout << array[i] << endl;
}
// C++11的遍历
for (auto& e : array)
e *= 2;
for (auto e : array)
cout << e << " " << endl;
string str("hello world");
for (auto ch : str)
{
cout << ch << " ";
}
cout << endl;
return 0;
}
二、string类的常用接口
string的常见构造
string(); //默认构造
string(const string& str);//拷贝构造
string(const string& str, size_t pos, size_t len = npos);//pos为拷贝的位置,len为拷贝的长度
string(const char* s);//生成字符串为s的复制品
string(const char* s, size_t n);//将字符串前n个进行初始化
string(size_t n, char c);//初始化n个为c的字符
string(InputIterator first, InputIterator last);
#include<iostream>
#include<string>
using namespace std;
//string(); //默认构造
//string(const string& str);//拷贝构造
//string(const string& str, size_t pos, size_t len = npos);//pos为拷贝的位置,len为拷贝的长度
//string(const char* s);//生成字符串为s的复制品
//string(const char* s, size_t n);//将字符串前n个进行初始化
//string(size_t n, char c);//初始化n个为c的字符
//string(InputIterator first, InputIterator last);
int main()
{
string s1;//默认构造
string s2("hello word");//生成这一字符串
string s3(s2);//拷贝构造
string s4(s2,6, 5);//从pos位置开始拷贝
string s5(s2, 5);//将字符串前n个进行初始化
string s6(8,'c');//初始化n个为c的字符
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
cout << s4 << endl;
cout << s5 << endl;
cout << s6 << endl;
return 0;
}
string的容量操作
void test_string3()
{
string s2("hello world");
cout << s2.length() << endl;
cout << s2.size() << endl;
cout << s2.max_size() << endl;
cout << s2.capacity() << endl;
TestPushBack();
string s3("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
//cout << sizeof(s2) << endl;
//cout << sizeof(s3) << endl;
}
size和length功能是一样的。
void TestPushBack()
{
string s;
size_t sz = s.capacity();
cout << "capacity changed: " << sz << '\n';
cout << "making s grow:\n";
for (int i = 0; i < 100; ++i)
{
s.push_back('c');
if (sz != s.capacity())
{
sz = s.capacity();
cout << "capacity changed: " << sz << '\n';
}
}
}
string的扩容在不同编译器下会有不同。
在这里引入reserve,这个函数可以为字符串预留空间。
void TestPushBack()
{
// reverse 反转 逆置
// reserve 保留、预留
string s;
// 提前开空间,避免扩容,提高效率
s.reserve(100);
size_t sz = s.capacity();
cout << "capacity changed: " << sz << '\n';
cout << "making s grow:\n";
for (int i = 0; i < 100; ++i)
{
s.push_back('c');
if (sz != s.capacity())
{
sz = s.capacity();
cout << "capacity changed: " << sz << '\n';
}
}
}
void test_string4()
{
string s2("hello worldxxxxxxxxxxxxx");
cout << s2.size() << endl;
cout << s2.capacity() << endl << endl;
s2.reserve(20);
cout << s2.size() << endl;
cout << s2.capacity() << endl << endl;
s2.reserve(28);
cout << s2.size() << endl;
cout << s2.capacity() << endl << endl;
s2.reserve(40);
cout << s2.size() << endl;
cout << s2.capacity() << endl << endl;
s2.clear();
cout << s2.size() << endl;
cout << s2.capacity() << endl << endl;
cout << typeid(string::iterator).name() << endl;
cout << typeid(string::reverse_iterator).name() << endl;
}
- size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一致,一般情况下基本都是用size()。
- clear()只是将string中有效字符清空,不改变底层空间大小。
- resize(size_t n) 与 resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,不同的是当字符个数增多时:resize(n)用0来填充多出的元素空间,resize(size_t n, char c)用字符c来填充多出的元素空间。注意:resize在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。
- reserve(size_t res_arg=0):为string预留空间,不改变有效元素个数,当reserve的参数小于string的底层空间总大小时,reserver不会改变容量大小。
string的元素访问和对象的修改操作
string s1("hello word");
cout << s1[1] << endl;//返回pos(下标)位置的字符
push_back('x');//在字符串后面尾插字符
s1.push_back('j');
s1.append("qqqqqqqqq");//在字符串后追加一个字符串
cout << s1 << endl;
s1 += 's';//在字符串后面追加字符串
s1 += "sdsda";
s1.insert(0, "ni");
cout << s1 << endl;
s1.insert(6, "hao");
cout << s1 << endl;
string s3("hello word");
//删除某一字符
//头删
s3.erase(0, 1);
cout << s3 << endl;
s3.erase(s3.begin());
cout << s3 << endl;
//尾部删除
s3.erase(s3.size() - 1, 1);
cout << s3 << endl;
s3.erase(--s3.end());
cout << s3 << endl;
//把字符串中的字符用其他字符串代替
s3.replace(5, 1, "xx");
cout << s3 << endl;
下面我们通过一个程序来了解string中的find函数,在一个字符串中找’ '并且用%代替。
void test4()
{
string s4("hello word hello bit");
size_t pos = s4.find(' ');//在s4这一字符串中找空格
while (pos != string::npos)//C++规定如果find没有找到会返回一个npos,find这里不是npos也就是找到了' '
//就进入while循环,进行替换。
{
s4.replace(pos, 1, "%");
pos= s4.find(' ');
}
cout << s4 << endl;
}
c_str简单来说是为了让C++兼容C语言
std::string 是C++标准库提供的字符串类,它封装了字符串操作并提供了很多方便的函数。然而,有时候我们需要将 std::string 转换为 C 风格的字符串(如 const char*),以便与一些仅支持 C 字符串的库(例如某些C标准库函数)兼容。
c_str() 函数返回一个 const char*,指向字符串对象的字符数据,保证了返回的C字符串是以空字符 ‘\0’ 结尾的。这使得它可以用于需要C风格字符串的地方。
subst函数是在str字符串中从pos位置开始,截取n个字符返回一个新的字符串。
string s5("test.cpp");
size_t pos = s5.find('.');
string s6 = s5.substr(pos);//在s5中从pos位置出发,截取n个字符,并将其返回s6。
cout << s6 << endl;
string类非成员函数
有一串代码,是计算一个字符串中最后一个单词的长度。
平常的字符串没有getline的话,直接输入的话会自动忽略空格,这时就要用到getline这样函数。在getline函数中这一字符串只有遇到换行符才能停止,也可以自定义遇到哪个符号停止。
int main()
{
string str;
getline(cin, str);
size_t pos = str.rfind(' ');
cout << str.size() - (pos + 1) << endl;
return 0;
}