Question

Existe-t-il une fonction de bibliothèque C qui renverra l'index d'un caractère dans une chaîne ?

Jusqu'à présent, tout ce que j'ai trouvé, ce sont des fonctions comme strstr qui renverront le caractère trouvé *, et non son emplacement dans la chaîne d'origine.

Était-ce utile?

La solution

je pense que

size_t strcspn ( const char * str1, const char * str2 );

c'est ce que tu veux.Voici un exemple tiré de ici:

/* strcspn example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] = "fcba73";
  char keys[] = "1234567890";
  int i;
  i = strcspn (str,keys);
  printf ("The first number in str is at position %d.\n",i+1);
  return 0;
}

Autres conseils

strstr renvoie un pointeur vers le caractère trouvé, vous pouvez donc utiliser l'arithmétique du pointeur :(Note:ce code n'a pas été testé pour sa capacité à compiler, il est à un pas du 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" */
}

MODIFIER:strchr n'est meilleur que pour un seul caractère.L'arithmétique du pointeur dit "Hellow !" :

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

Important: strchr() renvoie NULL si aucune chaîne n'est trouvée

Vous pouvez utiliser strstr pour accomplir ce que vous voulez.Exemple:

char *a = "Hello World!";
char *b = strstr(a, "World");

int position = b - a;

printf("the offset is %i\n", position);

Cela produit le résultat :

the offset is 6

Si vous n'êtes pas totalement lié au C pur et que vous pouvez utiliser string.h, il y a strchr()Vois ici

Écrivez votre propre :)

Code provenant d'une bibliothèque de traitement de chaînes sous licence BSD pour C, appelée zChaîne

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

Tu peux écrire

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

pour trouver l'indice de 'h' dans le brouhaha donné.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top