【C/C++】string类

string类的构造

#include <iostream>
#include <string>
using namespace std;

int main()
{
	//构造函数将string对象str1并初始化
	string str1("123456");
	cout << str1 << endl;
	
	//构造函数将string对象str2初始化为20个$字符组成
	string str2(20, '$');
	cout << str2 << endl;
	
	//复制构造函数将three初始化为 string 对象str1
	string str3(str1);
	cout << str3 << endl;
	
	str1 += "789";
	str2 = "abcdefg";
	string str4;
	str4 = str1 + str2;
	cout << str4 << endl;
	
	//将C语言风格字符串和一个整数座位参数,
	//整数表示要复制多少个字符
	char alls[] = "All's well that ends well";
	string str5(alls, 20);
	cout << str5 << "!\n";
	
	//构造函数模板 template<class Iter> string {Iter begin, Iter end};
	//构造函数将使用begin和end指向位置之间的值对string对象进行初始化
	string str6(alls + 6, alls + 10);
	cout << str6 <<endl;
	
	string str7(&str5[6], &str5[10]);
	cout << str7 << "...\n";
	
	//从str4的第3个字符(位置2)开始,将6个 字符复制到str8
	string str8(str4, 2, 6);
	cout << str8 << "in motion!" << endl;
	
	return 0;
}

输出结果

123456
$$$$$$$$$$$$$$$$$$$$
123456
123456789abcdefg
All's well that ends!
well
well...
345678in motion!

字符串C语言风格与string转换

string str_cpp;
char str_c[100];

C++中,string类能够自动将C语言字符串转换成string对象

str_cpp = str_c;

string类型转换成C语言字符串可以用string类的c_str()方法

const char *s = str.c_str();

猜你喜欢

转载自blog.csdn.net/de_se/article/details/94653840
今日推荐