在C-中的strpos如何工作

时间:2010-01-19 07:32:15

标签: c

我是C的新手。

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

5 个答案:

答案 0 :(得分:21)

这里有一个完整的代码段来解决您的问题。 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;
}

编辑:回答Vural问题:

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

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

答案 1 :(得分:14)

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

答案 2 :(得分:3)

是。它被称为strstr,与strpos类似(伪代码):

strpos(str, target) {
   res = strstr(str, target); 
   if (res == NULL) return false;
   else             return res - str;
}

答案 3 :(得分:1)

我已经从头开始编写了strpos()函数和position功能(就像PHP&#; s strpos()函数)。返回值将是搜索字符串的起始位置。请享用! :)

  

在此示例中,代码输出将为12

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

int strpos(char *haystack, char *needle, int pos);

int main(){

    printf("%d",strpos("abcdefabcdefabcdef asdfgavcabcddd","abc",10));

    return 0;
}

int strpos(char *haystack, char *needle, int pos){
    int i,j,check,result = -1;
    int len_needle=strlen(needle);
    int len_haystack=strlen(haystack);  
    i = pos;
    if (len_needle>len_haystack || *needle==NULL || i>(len_haystack-1)) return result;

    for(;i<len_haystack;i++){
        check = 0;
        for(j=0;j<len_needle;j++){
            if(haystack[i+j]==needle[j]){
                check++;
            }
        }           
        if(check==len_needle){
            result = i;
            break;
        }

    }
    return result;
}

答案 4 :(得分:0)

这是对Miere和Can Vural的回应。我无法添加评论,因此会将其添加为答案。

  

不应该是strpos(&#34; string&#34;,&#34; substring&#34;) - 可以Vural

     

在结构化编程中,你有indexOf(haystack,needle)。 Miere

在您的代码中,您有:

int strpos(char *haystack, char *needle)

但你也有:

(pos = strpos( "subsstring", "string")) 

我完全同意&#34; int strpos(char * haystack,char * needle)&#34;其中要搜索的字符串首先出现,搜索FOR的字符串是第二个。但对我来说,&#34; subsstring&#34; (在&#34中;一个是子串,一个是字符串&#34;),&#34;子串&#34;意味着IT是两者中较短的一个,并且你试图找到&#34; substring&#34; in&#34; string。&#34;

所以这一部分:

(pos = strpos( "subsstring", "string")) 

应该是:

(pos = strpos( "string" /*that which is being searched within/*, "substring" /*that which is being searched for in the previous parameter*/)) 

与:

相同
(pos = strpos( "haystack", "needle"))