华为机试——输出指定字段

华为2016校招提前批

题目:根据指定的分割符分割字符串,并输出指定的段

描述:根据指定的分隔符分隔字符串,并输出指定的段。如果指定的段超过分隔的段数,输出NULL

举例:
AAA?BBB?CCC??2
字符串为AAA?BBB?CCC?
分隔符为:?
指定的段位:2
字符串分隔为:AAA BBB CCC共三段,第二段字符串为:BBB
输入输出格式要求:
输入份额字符串长度小于128个字符,指定的段是一个正整数。
样例
输入:AAA?BBB?CCC??2
输出:BBB

//方法一:
#include<iostream>
#include<string>
#include<vector>
using namespace std;

int main()
{
    string str,s,tmp;
    vector<string> vs;
    getline(cin,str);
    int n;
    char ch;
    int len=str.size();
    n=str[len-1]-'0';
    ch=str[len-2];
    s=str.substr(0,len-2);
    string::size_type pos=0,pos2;

    while((pos2=s.find(ch,pos))!=string::npos)
    {
        tmp=s.substr(pos,pos2-pos);
    //  cout<<tmp<<endl;
        vs.push_back(tmp);
        pos=pos2+1;
        if(pos>s.size())
            break;
    }
    if(n>vs.size())
        cout<<"NULL"<<endl;
    else
        cout<<vs[n-1]<<endl;
}

//方法二:
#include<iostream>
#include<string>

using namespace std;

int main()
{
    string str,s;
    getline(cin,str);
    int len=str.size();
    int n=str[len-1]-'0';
    char ch=str[len-2];
    int count=1;
    for(int i=0;i<len-2;i++)
    {
        if(str[i]==ch)
            count++;
        if(count==n)
        {
            while(str[++i]!=ch)
            {
                cout<<str[i];
            }
            return 0;
        }
    }
    if(count<n)
        cout<<"NULL"<<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值