Tuesday, April 10, 2012

Program 8TH in C++

PROBLEM STATEMENT :

You are given a url in a format:
<protocol>://<hostname>:<port>/<filename>
eg. http://www.amazon.com/index.html
implement a function which takes url and do following operations on it:-
1. convert protocol & host name to lowercase.
2. If Url don't contain protocol ,then add http:// at the beginning of the url.
3. replace "//" by "/"
4. if Url contain file name, then remove the file name from the Url.

SOLUTION :

Assumption : The string is entered in proper format.

Character strings can be excluded but if entered, proper syntax is followed.


#include <iostream.h>
#include <cstdio>
#include <string.h>
#include <cstdlib>

using namespace std;

string convertUrl( string s)
{

int i=0;
int j=0;
string protocol="";
//Extracting protocol if present

for(i=0; i < s.length(); i++)
{
if(s[i] == ':')
{
if(s[i+1] == '/' && s[i+2] == '/')
{
protocol=s.substr(0,i+3);
j=i;
i+=3;
break;
}
}
}
//if protocol not present, then j=0, and hence i is set to 0 again.

if( j ==0)
{
i=0;
}

//Changing the case of host name to lower chars if in upper

while( s[i] != '/' && s[i] != '\0' && s[i] != ':')
{
if(s[i] >= 65 && s[i] <= 90)
{
s[i] += 32;
}
i++;
}
//moving from port portin to filename or end of string
if(s[i] == ':')
{
while( s[i] != '/' && s[i] != '\0')
{
i++;
}
}
//at the last slash, if present, filename is extracted out and s is set to string before that only.
if(s[i] == '/')
{
s=s.substr(0,i);
}
//entering protocol if not entered or not correct

if(protocol == "" && protocol != "http://" && protocol != "https://")
{
protocol="http://";
}
// removing one slash from protocol

if(protocol[protocol.length()-1] == '/' && protocol[protocol.length()-2] == '/')
{
protocol[protocol.length()-1]='\0';
}
//Changing protocol part to lower case

for( i=0; i < protocol.length(); i++)
{
if(protocol[i] >=65 && protocol[i]<=90)
{
protocol[i]+=32;
}
}
//merging the two strings on the basis of protocol already present or not

if(j!=0)
{
protocol += s.substr((j+3),s.length());
}
else
{
protocol += s.substr(j,s.length());
}
return protocol;

}

int main()
{
string url;

cout<<"\n\nEnter URL : ";
getline(cin,url,'\n');
cin.clear();
url=convertUrl(url);
cout<<"\n\nThe formatted URL is : "<<url<<endl<<endl;
}



No comments:

Post a Comment