Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

string

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?

like image 802
J. Berman Avatar asked Mar 20 '13 04:03

J. Berman


People also ask

How do you check if a string starts with a specific character?

The startsWith() method returns true if a string starts with a specified string. Otherwise it returns false . The startsWith() method is case sensitive. See also the endsWith() method.

How do you check if a string contains another string in c?

Search for string inside another string - strstrThe function strstr returns the first occurrence of a string in another string. This means that strstr can be used to detect whether a string contains another string. In other words, whether a string is a substring of another string.


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

like image 64
Aniket Inge Avatar answered Sep 29 '22 18:09

Aniket Inge