如何检查字符串是否以C中的某个字符串开头?

ax6ht2ek  于 2023-11-16  发布在  其他
关注(0)|答案(6)|浏览(196)

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

  1. char usUrl[MAX] = "http://www.stackoverflow"
  2. if(usUrl[0] == 'h'
  3. && usUrl[1] == 't'
  4. && usUrl[2] == 't'
  5. && usUrl[3] == 'p'
  6. && usUrl[4] == ':'
  7. && usUrl[5] == '/'
  8. && usUrl[6] == '/') { // what should be in this something?
  9. printf("The Url starts with http:// \n");
  10. }

字符串
或者,我考虑过使用strcmp(str, str2) == 0,但这一定非常复杂。
有没有一个标准的C函数可以做这样的事情?

pxy2qtax

pxy2qtax1#

  1. bool StartsWith(const char *a, const char *b)
  2. {
  3. if(strncmp(a, b, strlen(b)) == 0) return 1;
  4. return 0;
  5. }
  6. ...
  7. if(StartsWith("http://stackoverflow.com", "http://")) {
  8. // do something
  9. }else {
  10. // do something else
  11. }

字符串
您还需要#include<stdbool.h>,或者只需将bool替换为int

k4aesqcs

k4aesqcs2#

我的建议是:

  1. char *checker = NULL;
  2. checker = strstr(usUrl, "http://");
  3. if(checker == usUrl)
  4. {
  5. //you found the match
  6. }

字符串
只有当字符串以'http://'开头,而不是类似于'XXXhttp://'的字符串时,这才匹配
您也可以使用strcasestr,如果它在您的平台上可用。

ogsagwnx

ogsagwnx3#

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

  1. #include <stdio.h>
  2. #include <stddef.h>
  3. #include <stdbool.h>
  4. bool startsWith(const char *haystack, const char *needle) {
  5. for (size_t i = 0; needle[i] != '\0'; i++) {
  6. if (haystack[i] != needle[i]) {
  7. return false;
  8. }
  9. }
  10. return true;
  11. }
  12. int main() {
  13. printf("%d\n", startsWith("foobar", "foo")); // 1, true
  14. printf("%d\n", startsWith("foobar", "bar")); // 0, false
  15. }

字符串

展开查看全部
ie3xauqp

ie3xauqp4#

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

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

字符串

mutmk8jj

mutmk8jj5#

这个线程中的一些答案包含有效的答案,但是当没有必要这样做时,通过将解决方案 Package 到一个函数中,最终使事情变得非常复杂。答案相当简单:

  1. if( strncmp(stringA, stringB, strlen(stringB)) == 0 )
  2. {
  3. printf("stringA begins by stringB");
  4. } else {
  5. printf("stringA does not begin by stringB");
  6. }

字符串

lbsnaicq

lbsnaicq6#

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

相关问题