String.indexOf function in C

前端 未结 7 1383
Happy的楠姐
Happy的楠姐 2020-11-30 06:41

Is there a C library function that will return the index of a character in a string?

So far, all I\'ve found are functions like strstr that will return the found cha

相关标签:
7条回答
  • 2020-11-30 06:49

    strstr returns a pointer to the found character, so you could use pointer arithmetic: (Note: this code not tested for its ability to compile, it's one step away from pseudocode.)

    char * source = "test string";         /* assume source address is */
                                           /* 0x10 for example */
    char * found = strstr( source, "in" ); /* should return 0x18 */
    if (found != NULL)                     /* strstr returns NULL if item not found */
    {
      int index = found - source;          /* index is 8 */
                                           /* source[8] gets you "i" */
    }
    
    0 讨论(0)
  • 2020-11-30 06:52

    You can write

    s="bvbrburbhlkvp";
    int index=strstr(&s,"h")-&s;
    

    to find the index of 'h' in the given garble.

    0 讨论(0)
  • 2020-11-30 06:53

    If you are not totally tied to pure C and can use string.h there is strchr() See here

    0 讨论(0)
  • 2020-11-30 06:53

    Write your own :)

    Code from a BSD licensed string processing library for C, called zString

    https://github.com/fnoyanisi/zString

    int zstring_search_chr(char *token,char s){
        if (!token || s=='\0')
            return 0;
    
        for (;*token; token++)
            if (*token == s)
                return 1;
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-30 07:00

    EDIT: strchr is better only for one char. Pointer aritmetics says "Hellow!":

    char *pos = strchr (myString, '#');
    int pos = pos ? pos - myString : -1;
    

    Important: strchr () returns NULL if no string is found

    0 讨论(0)
  • 2020-11-30 07:00

    You can use strstr to accomplish what you want. Example:

    char *a = "Hello World!";
    char *b = strstr(a, "World");
    
    int position = b - a;
    
    printf("the offset is %i\n", position);
    

    This produces the result:

    the offset is 6
    
    0 讨论(0)
提交回复
热议问题