C++STL中string

string

string其实很像vector

string s的输出可以直接cout << s;

s.append(n,字符)或s.append(字符串):在s字符串末尾添加n个字符或一个字符串

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

int main(){
	
	string s(10,'#');
	
	cout << s << endl;
	
	s.append(3,'*');
	s.append("+++");
	
	cout << s;
	
	return 0;
} 

在这里插入图片描述

s.substr(a):截取第a个元素后所有元素

s.substr(a,b):截取第a个元素后的b个元素

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

int main(){
	
	string s; 
	s.append("abcdefghijklmn");
	
	cout << s << endl; 
	
	//截取第四个元素后的所有字符 
	cout << s.substr(4) << endl;
	
	//截取第七个字符后的3个字符 
	cout << s.substr(7,3) << endl;
	return 0;
} 

在这里插入图片描述

高版本的c++支持如下这种遍历字符串方式(我的C++98不支持)

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

int main(){
	
	string s; 
	s.append("abcdefghijklmn");
	
	for(char c : s){
		cout << c << endl;
	}
	
	return 0;
} 
输入字符串的三种方法
  • scanf("%s",s.data()):用的不多
  • cin >> s:有空格就不行了
  • getline(cin,s):能读一整行,用的最多
#include<bits/stdc++.h>
using namespace std;

int main(){
	
	string s; 
	
	//cin读整个句子
	cin >> s;
	cout << s << endl;
	
	return 0;
} 

在这里插入图片描述

可以发现只读进去了this,碰到空格就会出问题

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

int main(){
	
	string s; 
	
	//getline读一整行
	getline(cin,s);
	cout << s << endl;
	
	return 0;
} 

在这里插入图片描述

string的查找

s.find():返回字串在母串中的位置,如果母串中没有子串,则返回s.npos(是一个很大的整型数字)

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

int main(){
    string s("abcdabcd");
    
    cout << " s.npos:" << s.npos << endl;
    cout << " 没找到:" << s.find("jk") << endl;
    cout << " 从头开始子串出现的位置::" << s.find("cd") << endl;
    
    cout << " 找4号位置后子串出现的位置:" << s.find("cd",4);

	return 0;
}

在这里插入图片描述

s.find_first_of(子串):返回子串在母串中第一次出现的位置

s.find_last_of(子串):返回子串在母串中最后一次出现的位置

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

int main(){
    string s("abcdabcd");
    
    cout << " 子串首次出现位置:" << s.find_first_of("ab") << endl;
    cout << " 子串最后一次出现位置:" << s.find_last_of("ab") << endl;

	return 0;
}

在这里插入图片描述

s.rfind():从后往前反向查找,一般用正向查找和反向查找得到子串的位置不同来证明子串不唯一

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值