在C-中的strpos如何工作

Sup*_*ing 12 c

我真的很新C.

我想使用strpos函数,但它告诉我它不存在?

Mie*_*ere 23

这里有一个完整的代码片段来解决您的问题. PS:帮助还为时不晚.;)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NOT_FOUND -1

int main (){
    int pos = NOT_FOUND;
    if ( (pos = strpos( "subsstring", "string")) != NOT_FOUND )
        printf("found at %d\n", pos);
    else
        printf("not found!\n");
    return 0;
}

int strpos(char *haystack, char *needle)
{
   char *p = strstr(haystack, needle);
   if (p)
      return p - haystack;
   return NOT_FOUND;
}
Run Code Online (Sandbox Code Playgroud)

编辑:回答可以Vural问题:

不,我真的认为它会是这样的.在结构化编程范例中,通常的做法是将范围结构用作属于结构范围本身的每个函数的第一个参数.string.h中定义的strstr函数遵循相同的方法.

在OOP你有haystack.indexOf( needle ).在结构化编程中,你有indexOf( haystack, needle ).


小智 15

您正在寻找的功能可能是strstr或strchr.然后,您需要包含string.h.POSIX接口中没有strpos.