5-4学习笔记:字符串问题(1)

字符串:遍历、加密、统计、匹配
定义方式构造字符串

#include<bits/stdc++.h>
using namespace std;
int main(){
	string s0="Initial String"; 
	string s1;
	string s2(s0);
	string s3(s0,8,3);
	string s4("A character sequence");
	string s5("A character sequence",12);//其中12位
	string s6(10,'x');//十个重复的数字
	
	cout<<"s1 "<<s1<<endl;
	cout<<"s2 "<<s2<<endl;
	cout<<"s3 "<<s3<<endl;
	cout<<"s4 "<<s4<<endl;
	cout<<"s5 "<<s5<<endl;
	cout<<"s6 "<<s6<<endl;
	
}

在这里插入图片描述
字符串操作

#include<bits/stdc++.h>
using namespace std;
int main(){
	string str ="hello world";
	for(int i=0;i<str.size();i++){
		cout<<str[i];
	}
	string str1="to be a question";
	string str2="that is a";
	string str3="or not world";
	string str4;
	//插入 
	str4.insert(0,str1);
	cout<<"str4 "<<str4<<endl;
	str4.insert(6,str3,0,7);
	cout<<"str4 "<<str4<<endl;
	str4.insert(13,"to be");
	cout<<"str4 "<<str4<<endl;
	str4.insert(19,str2);
	cout<<"str4 "<<str4<<endl;
	
	str4.erase(19);//从19下标之后都不要了
	str4.erase(0,9);//从0开始删除9个 
	cout<<"str4: "<<str4<<endl;
	
	str4.clear();
	cout<<"str4: "<<str4<<endl;
	
	return 0;
}

在这里插入图片描述
字符串运算

#include<bits/stdc++.h>
using namespace std;

int main(){
	//字符串拼接 
	string str1="to be";
	string str2="not to be";
	string str3="that is a question";
	string str=str1+';';
	cout <<str<<endl;
	str =str+str2+';';
	cout <<str<<endl;
	str +=str3;
	cout <<str<<endl;
	
	str1="ab";
	str2="abc";
	str3="bcc";
	cout<<(str1<=str2)<<endl;
	cout<<(str2!=str3)<<endl;
	cout<<(str3<str1)<<endl;
} 

在这里插入图片描述

字符串函数

#include<bits/stdc++.h>
using namespace std;

int main(){
	string str1="hello world,end world";
	int length=str1.size();
	cout<<length<<endl;
	int position1 =str1.find("world");//从第0开始找 
	int position2 =str2.find("world",10);//从第10开始找 
	cout<<position1<<" "<<position2<<endl;
	//找字符用'' 
	position1=str1.find('a');//找不到返回-1 
	cout<<position1<<endl;
	//返回字符串子串函数
	string str2=str1.substr(13);//从这个开始到结尾 
	string str3=str1.substr(13,3);//只要其中一段 第二个参数是返回几个字符 
	cout<<str2<<endl<<str3<<endl;
	return 0; 
}

在这里插入图片描述

什么时候我能养成写博客的习惯!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值