【问题标题】:How to check if string starts with certain string in C?如何检查字符串是否以C中的某个字符串开头?
【发布时间】:2013-03-20 04:04:57
【问题描述】:

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

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");
}

或者,我考虑过使用strcmp(str, str2) == 0,但这一定很复杂。

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

【问题讨论】:

标签: c string


【解决方案1】:
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
}

您还需要#include<stdbool.h> 或将bool 替换为int

【讨论】:

  • 这个问题有很多不正确的答案。这是一个正常工作的。
  • return !strncmp(a, b, strlen(b));
【解决方案2】:

我建议这样做:

char *checker = NULL;

checker = strstr(usUrl, "http://");
if(checker == usUrl)
{
    //you found the match

}

仅当字符串以'http://' 开头而不是'XXXhttp://' 之类的开头时才会匹配

如果您的平台可用,您也可以使用strcasestr

【讨论】:

  • 即使开头不匹配,这也会一直检查到 usUrl 的结尾,这可能会导致性能很差。
【解决方案3】:

使用显式循环的解决方案:

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

【讨论】:

    【解决方案4】:

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

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

    【讨论】:

      【解决方案5】:

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

      【讨论】:

      • strstr 查找字符串中第一次出现的子字符串。有人可以做"hello http://www.stackoverflow" 并且strstr 仍然会返回指针(基本上是找到事件)。我看到这是另一个功能,但仍然没有回答用户的问题。
      猜你喜欢
      • 2018-12-27
      • 2011-06-13
      • 2011-01-11
      • 2011-05-04
      • 1970-01-01
      • 2017-11-27
      • 2010-12-25
      相关资源
      最近更新 更多