26

For example, to validate the valid Url, I'd 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've thought about using strcmp(str, str2) == 0, but this must be very complicated.

Is there a standard C function that does such thing?

J. Berman
  • 484
  • 1
  • 6
  • 13

5 Answers5

76
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 bool with int

SSpoke
  • 5,656
  • 10
  • 72
  • 124
Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
9

I would suggest this:

char *checker = NULL;

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

}

This would match only when string starts with 'http://' and not something like 'XXXhttp://'

You can also use strcasestr if that is available on you platform.

Rohan
  • 52,392
  • 12
  • 90
  • 87
  • 7
    this will check till the end of usUrl even if the beginnings don't match, this can have very bad performance. – Ali80 Jun 04 '19 at 23:19
1

The following should check if usUrl starts with "http://":

strstr(usUrl, "http://") == usUrl ;
Reno
  • 95
  • 1
  • 2
1

A solution using an explicit loop:

#include <stdio.h>
#include <stddef.h>
#include <stdbool.h>

bool startsWith(const char *haystack, const char *needle) {
    for (size_t i = 0; needle[i] != '\0'; i++) {
        if (haystack[i] != needle[i]) {
            return false;
        }
    }

    return true;
}

int main() {
    printf("%d\n", startsWith("foobar", "foo")); // 1, true
    printf("%d\n", startsWith("foobar", "bar")); // 0, false
}
tleb
  • 4,395
  • 3
  • 25
  • 33
-1

strstr(str1, "http://www.stackoverflow") is another function that can be used for this purpose.

Yasir Malik
  • 441
  • 2
  • 9
  • `strstr` finds the first occurrence of the substring in the string. Someone can do `"hello http://www.stackoverflow"` and the `strstr` will still return the pointer (basically finding the occurrence). I see this is another function but still does not answer the user's question. – Jack Murrow Oct 04 '20 at 01:09