华为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;
}