c/c++语言开发共享如何检查字符串是否以C中的某个字符串开头?

例如,要validation有效的Url,我想执行以下操作

char usUrl[MAX] = "https://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 https:// n"); } 

或者,我已经考虑过使用strcmp(str, str2) == 0 ,但这必须非常复杂。

是否有标准的C函数可以做这样的事情?

     bool StartsWith(const char *a, const char *b) { if(strncmp(a, b, strlen(b)) == 0) return 1; return 0; } ... if(StartsWith("https://stackoverflow.com", "https://")) { // do something }else { // do something else } 

    您还需要#include或者只需用#include替换bool

    我建议这样:

     char *checker = NULL; checker = strstr(usUrl, "https://"); if(checker == usUrl) { //you found the match } 

    这只会在字符串以'https://'开头而不是'XXXhttps://'

    如果您的平台上有可用的strcasestr ,也可以使用它。

    strstr(str1, "https://www.stackoverflow")是另一个可用于此目的的函数。

    以下应检查usUrl是否以“http://”开头:

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

      以上就是c/c++开发分享如何检查字符串是否以C中的某个字符串开头?相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/560119.html

      (0)
      上一篇 2021年1月27日
      下一篇 2021年1月27日

      精彩推荐