检查标题中的年份如果找到了年份之前的字符串egtestmovie,我该怎么办?
int main()
{
string title = "testmovie2015.mkv";
for (int year = 2000; year <= 2018; year++)
{
// code
}
}
答案 0 :(得分:1)
string
类有两个在这里很有用的功能:find
和substr
。
与to_string
一起,您可以使用它们:
#include <iostream>
#include <string>
int main() {
std::string title = "testmovie2015.mkv";
int y = 2015;
std::string year = std::to_string(y);
std::string::size_type n = title.find(year);
if (n != std::string::npos)
{
std::string a = title.substr(0, n);
std::cout << a << std::endl;
}
return 0;
}
答案 1 :(得分:-1)
这很有效。
#include <string>
#include <iostream>
using namespace std;
int main() {
char title[20] = "testmovie2015.mkv";
int year=0,i=0;
for(i=0;title[i]!='\0';i++){
if(isdigit(title[i])&&isdigit(title[i+1])&&isdigit(title[i+2])&&isdigit(title[i+3]))
{ year=1;
break;
}
}
if(year)
{
year=((title[i]-'0')*1000)+((title[i+1]-'0')*100)+((title[i+2]-'0')*10)+(title[i+3]-'0');
if(year>=2000&&year<=2018)
{ int k=0;
while(k<i)
{
cout<<title[k];
k++;
}
}
else
{
cout<<"Year found: "<<year<<", but out of given range";
}
}
else
{
cout<<"No year found in the string";
}
}