c++ string类 流处理(字符串的输入输出和基础函数简介)

使用string 类需要包含头文件:

#include

初始化方法: 

#include
#include

using namespace std;

int main()
{
	string s1("hello");
	string month="March";
	string s2(8,'x');
	cout<

string 的赋值

1)可以用 = 号赋值;

string s1("hello");
string s2;
s2=s1;
cout<

2)用assign成员函数复制


	string s1("hello");
	string s2;
	s2.assign(s1);
	cout<

string类常用函数:

length().用来读取string对象的长度;

getline(cin,str);用来读取包含空格的字符串;

此外string还支持流读取运算符(遇空格停止)

string s1("hello");
	cout<>s1;//输入hello girl
	cout<

另外compare函数可以用来比较string的大小 

substr函数可用来取字符串的字串 swap函数可以用来交换两个字符串


	string s1("hello");
	string s2;
	s2=s1.substr(2,4);
	cout<

find()函数可用来从前往后查找字串第一次出现的位置并返回,如果找不到则返回string::npos

rfind()则是从后往前找。find()函数还可以指定开始查找的位置,find("str",i),i就是起始位置的下标。

另外还有find_first_of()和find_last_of()等函数大家有兴趣的可以了解一下。

string s1("hello");
cout<

erase()函数可以用来删除string中的字符

	string s1("hello girl");
	s1.erase(5);//删除下标5之后的字符
	cout<

replace()函数可以用来替换string中的字符

string s1("hello girl");
s1.replace(6,9,"world");//将下标从6到9的字符换成“world”
cout<

insert()函数可以在string中插入字符

string s1("hello girl");
string s2("world ");
s1.insert(6,s2);//将s2插入s1下标为6的位置,此处s2可以用任意字符串代替
cout<

c_str()函数可以转换成c语言式char*字符串

string s1("hello girl");
printf("%s\n",s1.c_str());//输出hello girl

 

你可能感兴趣的:(c++基础)