Come consentire gli spazi nella stringa quando si cerca la posizione della sottostringa in C?

StackOverflow https://stackoverflow.com/questions/1622279

  •  06-07-2019
  •  | 
  •  

Domanda

Sono bloccato su una parte dei miei compiti, ho dovuto trovare l'occorrenza più giusta di una sottostringa all'interno di una stringa. Ho fatto la prima parte (posso trovare sottostringhe in stringhe di una sola parola), ma ora ho problemi con la seconda parte. Devo usare una versione modificata di getline per consentire stringhe di più parole (ovvero con spazi). Ecco il codice non modificato di getline () e anche strindex () modificato (rispettivamente). Mi piacerebbe anche una spiegazione, a volte ho difficoltà a capire il codice scritto.

EDIT: Quindi ho aggiornato il mio codice, eccolo :)

/* string index */

int strindex(char str[], char substr[]){

    int str_idx, sub_idx, k, c = -1;

    for (str_idx = 0; str[str_idx] != '\0'; str_idx++) {

        for (sub_idx = str_idx, k = 0; substr[k] != '\0' && str[sub_idx] == substr[k]; sub_idx++, k++)
            ;

        if (k > 0 && substr[k] == '\0')
            c = str_idx;

    }
    return c;
    return -1; //never reached?
}

/* getline 
*
* Variable Dictionary
* ctchars - character counter, increments once each time getchar() is called
* str_idx - current index of the string, starts at 0, increments with loop
* 
*/


getline(char str[], int lim){

    int ctchars, str_idx = 0;

    ctchars=getchar();

    for (str_idx; str_idx<lim-1 && ctchars !=EOF && ctchars!='\n'; ++str_idx)
        str[str_idx] = ctchars;

    if  (ctchars == '\n') {
        str[str_idx] = ctchars;
        ++str_idx;
    }


    str[str_idx] = '\0';
    return str_idx;

}
È stato utile?

Soluzione

Ho un paio di suggerimenti per te:

for (j=i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++);

Spezzalo; non stipare tutto nella struttura di controllo.

j = i;
k = 0;
for (;;) {
    if (t[k] == '\0') break;
    if (s[j] != t[k]) break;
    j++;
    k++;
}

Ottieni nomi migliori per le tue variabili.

haystack_inner_index = i; /* get a better name for `i` too */
needle_index = 0;
for (;;) {
    if (needle[needle_index] == '\0') break;
    if (haystack[haystack_inner_index] != needle[needle_index]) break;
    haystack_inner_index++;
    needle_index++;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top