STL快速入门学习教程之string的简单使用
STL常用的类和容器有一下几个:
string
vector
set
list
map
string
C语言中常用的方法如下:
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
//创建字符指针ch指向 Hello world,该字符指针指向的内容不可改变
char *ch = "Hello world";
//创建char类型的数组用于存储字符串Hello world,可修改字符串
char s1[20] = "Hello world";
char s2[] = "Hello world";
//动态内存分配大小为20*sizeof(char*)的空间
char *s3 = (char*)malloc(20 * sizeof(char *));
gets_s(s3,20); //键盘等待输入
//输出
cout << ch << endl;
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
free(s3); //释放malloc分配的内存空间
system("pause");
return 0;
}
**C++标准库中加入可变长字符串string,由头文件#include< string>**提供
string初始化有两种方式:
1.使用”=“进行拷贝初始化
2.直接初始化
我们来看看下面的例子:
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
string s1; //初始化字符串,空字符串
string s2 = s1; //拷贝初始化,深拷贝字符串
string s3 = "Hello world"; //直接初始化,s3存了字符串Hello world
string s4(10, 'a'); //s4存放的字符串的10个a,即aaaaaaaaaa
string s5(s4); //拷贝初始化,深拷贝字符串
string s6("I am Lihua"); //直接初始化
string s7 = string(6, 'c'); //拷贝初始化,s7中6个c,即cccccc
system("pause");
return 0;
}
string的一些操作:
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
string s1; //初始化字符串,空字符串
string s2 = s1; //拷贝初始化,深拷贝字符串
string s3 = "Hello world"; //直接初始化,s3存了字符串Hello world
string s4(10, 'a'); //s4存放的字符串的10个a,即aaaaaaaaaa
string s5(s4); //拷贝初始化,深拷贝字符串
string s6("I am Lihua"); //直接初始化
string s7 = string(6, 'c'); //拷贝初始化,s7中6个c,即cccccc
//string的各种操作
string s8 = s3 + s6; //将两个字符串合并成一个
s3 = s6; //将s6中的元素赋值给s3,此时s3="I am Lihua"
cin >> s1;
//输出
cout << s2 << endl;
cout << s3 << endl;
cout << s4 << endl;
cout << s5 << endl;
cout << s6 << endl;
cout << s7 << endl;
cout << s8 << endl;
cout << "s7 size = " << s7.size() << endl; //字符串长度,不包括结束符
cout << (s2.empty() ? "This string is empty" : "This string is not empty") << endl;;
system("pause");
return 0;
}
文章版权说明
一:教程为个人编写,对个人真实有效,但不保证对所有人有效,出现任何问题或是经济损失将与本人无关
二:更多关于本人的教程请至:152.136.70.33