string类 简介

1、string类简介

  • string 类是模板类:typedef basic_string<char> string;
  • 使用string类要包含头文件 :<string>

2、string类的初始化

(1)正确的初始化:
  • string s1("Hello");
  • string month = "March";
  • string s2(8,'x');
(2)错误的初始化:
  • string error1 = 'c';
  • string error2('u');
  • string error3 = 22;
  • string error4(8);

注意:可以将字符赋值给string对象,但是不能用字符够初始化。

3、string举例

#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[ ]){
	string s1("Hello");
	cout << s1 << endl;
	string s2(8,'x');
	cout << s2 << endl;
	string month = "March";
	cout << month << endl;
	string s;
	s='n';
	cout << s << endl;
	return 0;
}
/*
输出:
Hello
xxxxxxxx
March
n
*/
原文地址:https://www.cnblogs.com/lasnitch/p/12764224.html