C++必修:STL用法之string
✨✨ 欢迎大家来到贝蒂大讲堂✨✨
🎈🎈养成好习惯,先赞后看哦~🎈🎈
所属专栏:C++学习
贝蒂的主页:Betty’s blog
1. C/C++中的字符串
1.1. C语言中的字符串
在 C 语言中,字符串是由字符组成的字符数组,以空字符 '\0' 作为结束标志。由于数组特点,字符串的大小在定义数组时就已经确定,无法更改。
//数组大小为20 char str[20] = "hello betty!\n";
当然我们可以通过动态内存分配来来解决这个问题,但无疑非常繁琐。
void Test1()
{
char* str = NULL;
int len = 0;
// 初始分配一些内存
str = (char*)malloc(10 * sizeof(char));
if (str == NULL) {
perror("malloc fail");
return 1;
}
strcpy(str, "Hello");
len = strlen(str);
// 根据需要扩展字符串
str = (char*)realloc(str, (len + 6) * sizeof(char));
if (str == NULL) {
perror("realloc fail");
return 1;
}
strcat(str, " World");
printf("%s\n", str);
//最后释放内存
free(str);
}
1.2. C++中的字符串
虽然C++兼容C语言,在C++中仍然可以使用C语言的字符串,但是C++自己实现了一个关于处理字符串的类–string,它提供了许多方便的操作和功能,使得字符串的处理更加安全和高效。下面是一个简单的string的使用:
void Test2()
{
string str = "hello betty!";
cout
string s1 = "hello betty!";
//普通迭代器
string::iterator it = s1.begin();//指向第一个位置
while (it != s1.end())
{
cout
cout
string s1 = "hello betty!";
//普通反向迭代器
string::reverse_iterator rit = s1.rbegin();//指向最后一个字符位置
while (rit != s1.rend())
{
cout
cout
//1. 使用我们的默认构造函数,不需要传参。
string s1;
s1 = "hello betty!";
//2. 使用的是拷贝构造来初始化。
string s2(s1);
//3. 使用一个string的某段区间初始化,其中pos是字符串下标,npos是指无符号整数的最大值。
string s3(s2, 1, 7);
//4. 使用的是某个字符数组初始化。
string s4("hello world!");
//5. 使用的是某个字符数组前n个字符来初始化
string s5("hello world!", 5);
//6. 使用的是n个c字符初始化。
string s6(7, 'a');
//7. 使用的是某段迭代器区间初始化。
string s7(s1.begin(), s1.end());
//赋值运算符重载初始化
string s8 = "hello betty!";
cout
string s("hello betty!");
cout
string s;
size_t sz = s.capacity();
cout
s.push_back('c');
if (sz != s.capacity())
{
sz = s.capacity();
cout
string s1("");//空串
string s2("hello ");
if (s1.empty())
{
cout
cout
cout
cout
string s1("hello world!");
cout
cout
string s1("hello world!");
cout
string s1("hello world!");
cout
string s1("hello betty!");
for (int i = 0; i
免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

