How to check if a line starts with a specific line in C?

For example, to check a valid Url, I would like to do the following

char usUrl[MAX] = "http://www.stackoverflow"

if(usUrl[0] == 'h'
   && usUrl[1] == 't'
   && usUrl[2] == 't'
   && usUrl[3] == 'p'
   && usUrl[4] == ':'
   && usUrl[5] == '/'
   && usUrl[6] == '/') { // what should be in this something?
    printf("The Url starts with http:// \n");
}

Or, I was thinking about using strcmp(str, str2) == 0, but it should be very difficult.

Is there a standard C function that does such a thing?

+5
source share
4 answers
bool StartsWith(const char *a, const char *b)
{
   if(strncmp(a, b, strlen(b)) == 0) return 1;
   return 0;
}

...

if(StartsWith("http://stackoverflow.com", "http://")) { 
   // do something
}else {
  // do something else
}

You also need #include<stdbool.h>or just replace boolwithint

+25
source

I would suggest the following:

char *checker = NULL;

checker = strstr(usUrl, "http://");
if(checker == usUrl)
{
    //you found the match

}

This will only match when the line starts with 'http://', and not something like'XXXhttp://'

You can also use strcasestrif it is available on your platform.

+6
source

strstr(str1, "http://www.stackoverflow") - , .

0

Next, check if usUrl is running with "http: //":

strstr(usUrl, "http://") == usUrl ;
0
source

All Articles