Reputation: 6519
Say I had the following code:
char url[63] = {'\0'};
scanf("%s", url);
And the user is asked to submit a url. I need to remove the characters that are typically at the beginnings of url such as http://, ftp://, etc...
I could check for the existence of "://" in the character array using a for loop like so:
int i;
for (i=0;i<strlen(url);i++) {
if (url[i] == ':' && url[i+1] == '/' && url[i+2] == "/") {
// Super cool code here...
}
}
But say I wanted to delete the :// and everything that came before it? How would I accomplish that? So that if the user entered:
The output would be:
www.google.com
And a similar result if ftp:// were used.
Upvotes: 0
Views: 2570
Reputation: 16406
const char* ssc = strstr(url, "//:");
if (ssc)
{
const char* withoutProtocol = ssc + 3;
// do something with withoutProtocol
}
Upvotes: 0
Reputation: 6834
All you need is:
int i;
for (i=0;i<strlen(url) - 2;i++) {
if (url[i] == ':' && url[i+1] == '/' && url[i+2] == '/') {
// Super cool code here...
return &url[i+3];
}
}
To create a copy:
char* getInteresting(char* url)
{
int i = 0;
for (i=0;i<strlen(url) - 2;i++) {
if (url[i] == ':' && url[i+1] == '/' && url[i+2] == '/') {
// Super cool code here...
int len = strlen(url) - (i+2);
char* copy = (char*)malloc(len + 1);
strcpy(copy, url + i + 3);
return copy;
}
}
}
Plus: a lot more checking through the error cases!
Upvotes: 1
Reputation: 3887
Usually the easiest way to do this sort of thing in C is to not actually change the original array at all, but instead to create another char *
pointer to the first part of the string you actually care about. So....
int i;
char *interesting_stuff;
for (i=0;i<strlen(url);i++) {
if (url[i] == ':' && url[i+1] == '/' && url[i+2] == "/") {
interesting_stuff = url + i + 3;
}
}
and then go on to do things with interesting_stuff
and leave url
alone. (Be aware that it's a pointer into the same array, so if you overwrite url
, you will lose interesting_stuff
too.)
BTW, the bounds on that for
loop will get you in trouble. You potentially look two characters past the end of the string, and my modification makes that problem a bit worse. You need to check the length of the string first and be sure that you don't go past the point in the string where ://
followed by some useful data could be found. In other words, you want to constrain your loop to strlen(url) - 4
except be careful if url
is shorter than 4 characters.
Upvotes: 1