STL simple to use Quick Start tutorial of learning string

STL simple to use Quick Start tutorial of learning string

STL commonly used classes and several vessels have it:

string
vector
set
list
map

string

C language commonly used method is as follows:

#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 ++ Standard Library added variable-length string string, header file #include <string> ** provide

string initialized in two ways:
1. "=" Initialization copying
2. Direct Initialization

Let's look at the following example:

#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 of some operations:

#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;
}

Copyright Articles

A: writing tutorials for individuals, for individuals real and effective, but does not guarantee work for everyone, any problems or economic loss would I have nothing
II: More about my tutorial go to: 152.136.70.33

Guess you like

Origin blog.csdn.net/qq_38937025/article/details/90900532