c++---stirng

1.使用string类之前,需要加上头文件

#include<string>

2.string的四种初始化方法

//4种初始化方法 
    string s1;//没有小括号,调用string默认的构造函数 ,创建空字符串
    string s2("hello");// 小括号就是调用string对象的构造函数 
    string s3(s2);
    string s4(10,'a');//10个a

3.string的输入

//string s;
    //cin>>s;//cin可忽略起始位置的空白,例如输入“ hello world”,只输出“hello” 
//    cout<<s<<endl; 
    cout<<"Please enter your name:"<<endl;
    string name;
    getline(cin,name); //读取一行字符串带空格
    cout<<name<<endl; 
    
    string line;
    while(getline(cin,line))//getline遇到换行符结束,不输出换行符 
    cout<<line<<endl;//ctr+z终止输入 

4.string的比较

字符串的比较: ==、>、<,//汉字基本按拼音字母排列

str.size() 返回字符串字符个数,‘\0’不在计算范围内

str.empty(),返回一个bool值,判断str是否为空字符串

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string s1,s2;
	cout<<"Enter two strings:"<<endl;
	cin>>s1>>s2;
	if(s1==s2)
	{
		cout<<"They are equal."<<endl;
	
	}
	else if(s1<s2)
		{
			cout<<"\""<<s1<<"\""<<" is smaller than \""<<s2<<"\""<<endl;
		}
		else
		{
			cout<<"\""<<s2<<" is bigger than "<<s1<<"\""<<endl;
		}
	//字符串长度比较
	string s3,s4;
	cout<<"输入两个string:"<<endl;
	cin>>s3>>s4;
	string::size_type len1,len2;
	len1=s3.size(); //返回字符串字符个数,‘\0’不在计算范围内
	len2=s4.size();
	 
	 if(len1==len2) 
	 cout<<"They are equal."<<endl;
	 else if(len1<len2)
	 cout<<"\""<<s3<<"\""<<" is smaller than \""<<s4<<"\""<<endl;
	 else
	cout<<"\""<<s3<<"\""<<" is bigger than \""<<s4<<"\""<<endl;
	 return 0;
 } 

5.string中

str[i],str.at(i)指定字符

	string s("string");
	cout<<s[1]<<endl;//字符串中的特定字符 
	cout<<s.at(1)<<endl;

6.string的拼接

#include <iostream>
#include <string>
using namespace std;
int main()
{
	string a("张飞");
	string b("刘备"); 
	a=b;        //字符串赋值
	 
	 //字符串加法,即字符串链接 
	string s1("hello,");
	string s2(" world!");
	string s3=s1+s2;
	cout<<s3<<endl;
	s1+=s2;
	cout<<s1<<endl;
	
	//string s4="hello"+", "; Invalid,string相加
	//加号不能全为字面值,其中一个需要是string变量
	string s4="hello"+s2+", "; //valid
	cout<<"s4"<<s4<<endl; 
	string s5;	
	return 0;
 } 

7.string的翻转

#include<algorithm>

reverse(str.begin(),str.end());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值