看上去很簡單的一道題,可是錯的次數卻不少。
題目要求是將一串字母轉化成網址——形如格式http(ftp)://xxx.ru/xxxx的樣子,看上去很簡單,可是還是很容易出錯。
剛開始找的時候是按照尋找第一組http/ftp,然後尋找第一個ru,構成網址,但是報錯了,反例如下:httpruc
所以不能尋找第一個網址,也就是說盡量避免.ru之前沒有東西,這樣是不合法 的。然後注意http是四個字符,ftp只有三個字符,所以不能固定。。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string tar,res;
string tarstack;
int propos=0,ctpos=0;
cin>>tar;
if(tar[0]=='h')
{
tarstack="http";
}
if(tar[0]=='f')
{
tarstack="ftp";
}
ctpos=tar.find("ru",tarstack.length()+1); //5是不行的,慣性思維不可
if(tar[0]=='h')
{
cout<<tarstack<<"://";
for(int i=4;i<ctpos;i++)
{
cout<<tar[i];
}
cout<<".ru";
if(ctpos+2==tar.length())
cout<<endl;
else
{
cout<<"/";
for(int i=ctpos+2;i<tar.length();i++)
{
cout<<tar[i];
}
cout<<endl;
}
}
else if(tar[0]=='f')
{
cout<<tarstack<<"://";
for(int i=3;i<ctpos;i++)
{
cout<<tar[i];
}
cout<<".ru";
if(ctpos+2==tar.length())
cout<<endl;
else
{
cout<<"/";
for(int i=ctpos+2;i<tar.length();i++)
{
cout<<tar[i];
}
cout<<endl;
}
}
return 0;
}
//范例:httpruhhphhhpuhruruhhpruhhphruhhru