字符串基础题2道-NYOJ-113(字符串替换)-519(密码发生器)

题目链接:
http://acm.nyist.net/JudgeOnline/problem.php?pid=113
http://acm.nyist.net/JudgeOnline/problem.php?pid=519

113:
这个题两种做法,分别是常规做法与STL做法;
其中常规做法没什么好讲,STL做法使用到replace()函数与find()函数;

常规做法:

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int main()
{
    char str[1050];
    while(gets(str))
    {
        int l=strlen(str);
        for(int i=0;i<l;i++)
        {
            if(str[i]=='y'&& str[i+1]=='o' && str[i+2]=='u')
            {
                cout<<"we";
                i+=2;
            }
            else            
            cout<<str[i];
        }
        cout<<endl;
    }
    return 0;
}

STL做法:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
    string ch,ch1="we";
    getline(cin,ch);
    while(ch!="")
    {
        int l=ch.length();
        string::size_type it; //声明string类型的迭代器
        it=ch.find("you"); 
        while(it<l) //注意结束条件
        {
            ch.replace(ch.begin()+it,ch.begin()+it+3,ch1.begin(),ch1.end());
            it=ch.find("you");
        }
        l=ch.length();
        cout<<ch<<endl;
        getline(cin,ch);
    }
    return 0;
}

519:
这个题关键是如何实现在题目中提到的缩位操作,我是直接写的递归实现;

代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
char str[105];
int num[6];
int ans[6];
int sum_all(int n)  //递归实现
{
    int sum=0;
    if(n<10)
        return n;
    else 
    {
        while(n>=10)
        {
            sum+=n%10;
            n/=10;
        }
        sum+=n%10;
        if(sum>=10)
            n=sum_all(sum);
        else 
            n=sum;
    }
    return n;
}
int main()
{ 
    int T;
    cin>>T;
    getchar();
    while(cin>>str)
    {
        getchar();
        memset(num,0,sizeof(num));
        int l=strlen(str);
        for(int i=0;i<l;i++)
            num[i%6]+=str[i];
        for(int i=0;i<6;i++)
            ans[i]=sum_all(num[i]);
        for(int i=0;i<6;i++)
        cout<<ans[i];
        cout<<endl;
        memset(str,0,sizeof(str));
    }
    return 0;
}

仅代表个人观点,欢迎交流探讨,勿喷~~

这里写图片描述
PhotoBy:WLOP

http://weibo.com/wlop

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值