Domanda

Esiste una funzione della libreria C che restituirà l'indice di un carattere in una stringa?

Finora, tutto quello che ho trovato sono funzioni come strstr che restituiranno il carattere trovato *, non la sua posizione nella stringa originale.

È stato utile?

Soluzione

penso che

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

è quello che vuoi.Ecco un esempio tratto da Qui:

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

Altri suggerimenti

strstr restituisce un puntatore al carattere trovato, quindi puoi usare l'aritmetica del puntatore:(Nota:questo codice non è stato testato per la sua capacità di compilazione, è a un passo dallo pseudocodice.)

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" */
}

MODIFICARE:strchr è migliore solo per un carattere.L'aritmetica del puntatore dice "Ciao!":

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

Importante: strchr() restituisce NULL se non viene trovata alcuna stringa

Puoi usare strstr per ottenere ciò che desideri.Esempio:

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

int position = b - a;

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

Questo produce il risultato:

the offset is 6

Se non sei totalmente legato al C puro e puoi usare string.h c'è strchr()Vedere qui

Scrivi il tuo :)

Codice da una libreria di elaborazione di stringhe con licenza BSD per C, chiamata 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;
}

Tu puoi scrivere

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

per trovare l'indice di 'h' nella confusione data.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top