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

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

#include<string>

初始化方法: 

#include<iostream>
#include<string>

using namespace std;

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

	string s;
	s='n';//可以将字符值给string对象
	cout<<s<<endl;//n
	return 0;
}

string 的赋值

1)可以用 = 号赋值;

string s1("hello");
string s2;
s2=s1;
cout<<s2;//输出hello

2)用assign成员函数复制


	string s1("hello");
	string s2;
	s2.assign(s1);
	cout<<s2;//输出hello
	//从s1中下标为0的字符开始复制3个字符
	s2.assign(s1,0,3);
	cout<<s2;//输出hel
	return 0;

string类常用函数:

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

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

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

string s1("hello");
	cout<<s1<<' '<<s1.length()<<endl;//hello  5
	getline(cin,s1);//输入hello girl
	cout<<s1<<' '<<s1.length()<<endl;//输出为hello girl 10
	cin>>s1;//输入hello girl
	cout<<s1<<' '<<s1.length()<<endl;//输出仍为hello  5

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

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


	string s1("hello");
	string s2;
	s2=s1.substr(2,4);
	cout<<s2<<endl;//输出llo
	s1.swap(s2);
	cout<<s1<<" "<<s2<<endl;//输出llo hello

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

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

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

string s1("hello");
cout<<s1.find("ll",1)<<endl;//输出2

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

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

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

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

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

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

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

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

 

  • 17
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值