string 容器的常见用法详解

1.在C语言中,一般使用字符数组 char str[]来存放字符串,但是使用字符数组有时会显得操作麻烦,而且容易因经验不足而产生一些错误。为了使编程者可以更方便地对字符串进行操作,在C++中引入 string 类型。

如果要使用string,需要添加string头文件,即 #include<string> (注意 string.h 和string 是不一样的头文件)。除此之外,还需要在头文件下面加上一句:“using namespace std;” 。

2. 如果要读入和输出整个字符串,则只能用 cin 和  cout ,具体解释和操作如下:

#include<stdio.h>
#include<string.h>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	//string str="ahgdfshgw";
	string str;
	cin>>str;
	for(int i=0;i<str.length();i++)
	{
		cout<<str[i]<<endl;
	}
	cout<<str<<endl;
	printf("%s\n",str.c_str());
	//通过迭代器访问
	for(string::iterator it=str.begin()+2;it!=str.end();it++)
	{
		printf("%c",*it);
	} 
	cout<<endl;
	string str1="hdsjdlk";
	string str2="shjaks";
	str1=str1+str2;          //string的加法,可以讲两string直接拼接起来 
	cout<<str1<<endl;
	//可以直接进行比较大小,比较规则是字典序
	string str11="aa",str12="aaa",str3="abc",str4="xyz";
	if(str11<str12)  cout<<"ok1"<<endl;
	if(str11!=str3)  cout<<"ok2"<<endl;
	if(str4>=str3)  cout<<"ok3"<<endl;
	//可以进行访问长度
	cout<<str.length()<<endl;
	//string 的 insert() 函数有多种写法这里给出两种写法:
	string t1="abcxyz",t2="opq";
	t1.insert(3,t2);
	t1.insert(t1.begin()+3,t2.begin(),t2.end());   //在t1的3号位(即 c 和 x 之间)插入 t2; 
	t1.erase(t1.begin()+3);       //单个删除
	t1.erase(t1.begin()+2,t1.end()-1);			//区间删除 
	t1.erase(3,2);            //删除从3号位开始的2个字符  
	t1.clear();							//全部清除 
	string t3="Thank you for your smile.";
	cout<<t3.substr(0,5)<<endl;
	cout<<t3.substr(14,5)<<endl;
	cout<<t3.substr(19,5)<<endl; 
	cout<<t1<<endl; 
	string t4="you";
	string t5="me";
	if(t3.find(t4) !=string::npos)    // 从t4 是 t3 的子串时,返回其在 t4 中第一次出现的位置;如果 t4 不是 t3 的子串 ,那么返回 string::npos。 
	{
		cout<<t3.find(t4)<<endl;	
	}
	if(t3.find(t4,7)!=string::npos)  		// 从 t3 的 7 号位 开始匹配 t4 返回值与上相同 
	{
		cout<<t3.find(t4,7)<<endl;
	}
	if(t3.find(t5)!=string::npos)	
	{
		cout<<t3.find(t5)<<endl;
	}
	else
	{
		cout<<"I know there is no position for me."<<endl;
	} 
	string s1="Maybe you will turn around.";
	string s2="will not";
	string s3="surely";
	cout<<s1.replace(10,4,s2)<<endl;			//把 s1 10号位开始,长度为 len 的子串 替换为 s2; 
	cout<<s1.replace(s1.begin(),s1.begin()+5,s3)<<endl;   //把 s1 的迭代器[it1,it2)范围的子串替换为 s3 
	return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风遥~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值