关于string型的处理——pta L1常用

本文介绍了如何使用C++进行字符串的输入、截取、字符查找、子串搜索和翻转,包括`getline`函数的用法、`substr`函数的应用,以及`find`和`reverse`等方法。通过实例演示了字符串处理的基本技巧。
摘要由CSDN通过智能技术生成

1.关于带空格字符串函数的输入

a.getline(cin,str);
b.getline(cin,str,c);(c为字符。)

#include<bits/stdc++.h>
using namespace std;
int main()
{
	string str1,str2;
	getline(cin,str1);            //输入带空格的字符串,当输入空格的时候终止 
	getline(cin,str2,'D');        //输入带空格的字符串,当输入‘D’的时候终止
	
	cout<<str1<<endl;             
	cout<<str2<<endl;
}

运行结果:

运行结果

2.关于字符串的截取
截取第a到第b个的字符串。
str.substr(a,b); substr从英文层面上很好理解,也就是子串呗。

#include<bits/stdc++.h>
using namespace std;
int main()
{
	string str;
	cin>>str;
	cout<<str.substr(1,5)<<endl;
}

运行结果:
截取字符串

3.一些字符串的处理
a.字符查找:
str.find©;

#include<bits/stdc++.h>
using namespace std;
int main()
{
	string str;
	cin>>str;
	cout<<str.find('w')<<endl;
	
}

运行结果:
在这里插入图片描述
b.字符串查找
str.find(str1);(str1为你想要查找的字符串);

#include<bits/stdc++.h>
using namespace std;
int main()
{
	string str;
	cin>>str;
	//查找一个字符串,如果找到,输出他的下标,如果没找到,输出负一
	long long int index=str.find("world");
	if(index<str.length())
	{
		cout<<index<<endl;
	}	
	else
	{
		cout<<"-1"<<endl;
	}
}

运行结果:
找到
没找到

c.字符串翻转输出:
reverse(str.begin(),str.end());

#include<bits/stdc++.h>
using namespace std;
int main()
{
	string str="helloworld";
	reverse(str.begin(),str.end());
	cout<<str<<endl;
}

运行结果:
反转输出
雪中悍刀行
有我在,天下无不可之事。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值