J. Berman
J. Berman

Reputation: 534

How to check if string starts with certain string in C?

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?

Upvotes: 30

Views: 63125

Answers (6)

Daniel J.
Daniel J.

Reputation: 366

Some answers in this thread contain valid answers, but end up unnecesarily complicating things by wrapping the solution into a function when there is no need to do that. The answer if rather simple:

if( strncmp(stringA, stringB, strlen(stringB)) == 0 )
{
    printf("stringA begins by stringB");
} else {
    printf("stringA does not begin by stringB");
} 

Upvotes: 0

tleb
tleb

Reputation: 4596

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
}

Upvotes: 1

Reno
Reno

Reputation: 113

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

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

Upvotes: 0

Aniket Inge
Aniket Inge

Reputation: 25705

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

Upvotes: 78

Rohan
Rohan

Reputation: 53326

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.

Upvotes: 8

Yasir Malik
Yasir Malik

Reputation: 439

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

Upvotes: -2

Related Questions