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

后端 未结 5 1543
遥遥无期
遥遥无期 2021-01-04 03:42

For example, to validate the valid Url, I\'d like to do the following

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

if(usUrl[0] == \'h\'
   && usUr         


        
相关标签:
5条回答
  • 2021-01-04 03:58

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

    0 讨论(0)
  • 2021-01-04 04:05

    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
    }
    
    0 讨论(0)
  • 2021-01-04 04:15

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

    strstr(usUrl, "http://") == usUrl ;
    
    0 讨论(0)
  • 2021-01-04 04:19
    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

    0 讨论(0)
  • 2021-01-04 04:21

    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.

    0 讨论(0)
提交回复
热议问题