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

后端 未结 5 1568
遥遥无期
遥遥无期 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 04:05

    A solution using an explicit loop:

    #include 
    #include 
    #include 
    
    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
    }
    

提交回复
热议问题