字符串编辑

Go CSP-S!  •  5年前


前两次的出错是因为,没有考虑到找不到字符的情况。

最后解决了这种情况就通过了。

下面简单分析一下代码:变量的定义就不说了,因为这个看懂题目之后就能得出。下面说一下string.erase()函数和string.find_first_of()函数,这两个函数都是String类里面的内置函数。1.string.erase(pos,n)  //删除从pos开始的n个字符 2.string.erase(pos) //删除pos处的一个字符(pos是string类型的迭代器)。3.find_first_of 函数最容易出错的地方是和find函数搞混。它最大的区别就是如果在一个字符串str1中查找另一个字符串str2,如果str1中含有str2中的任何字符,则就会查找成功,而find则不同。4.其中string:npos是个特殊值,说明查找没有匹配。

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;

int main()
{
int i,j,k,len;
string s,c1,c2,c3;
size_t p;

getline(cin,s),len=s.length(),c3=s[len];
for(i=0;i<len;i++)
if(s[i]=='.')
break;
s.erase(i+1),len=s.length();

cin>>c1;
switch(c1[0])
{
case 'D':cin>>c2;
p=s.find_first_of(c2);
if(p==string::npos)
cout<<"Not exist"<<endl;
if(p<len)s.erase(p,1);
break;
case 'I':cin>>c2>>c3;
p=s.find_last_of(c2);
if(p==string::npos)
cout<<"Not exist"<<endl ;
s.insert(p,c3);
break;
case 'R':cin>>c2>>c3;
p=s.find_first_of(c2);
if(p==string::npos)
cout<<"Not exist"<<endl ;
while(p!=string::npos)
{
s[p]=c3[0];
p=s.find_first_of(c2,p+1);
}
break;
}
cout<<s<<endl;
return 0;
}
 


评论:

请先登录,才能进行评论