Domanda

Sto scrivendo un piccolo programma in C che leggerà l'input dalla console. Quindi inseriscilo in un array di caratteri. Dopodiché devo dividere l'array in parole. Non sono sicuro di come farlo. Finora ho inserito l'input in un array di caratteri. Devo sapere se esiste un modo per tokenizzare basato su un carattere vuoto. O qualsiasi altro suggerimento su come gestire questo problema. Grazie.

campione:

input: questo è solo un test

array: [t, h, i, s,, i, s,, o, n, l, y,, a, t, e, s, t, null]

Vorrei ottenere un array String [questo, è, solo, un, test, null]

main() {

    char msg[50], ch;
    int i = 0;

    printf("***Reading words in your input*****\n\n");
    printf("Type something terminated by ENTER button\n");

    while ((ch = getchar()) != '\n')
        msg[i++] = ch;

    msg[i] = '\0';

    i = 0;

    while (msg[i] != '\0')
        putchar(msg[i++]);
    printf("\n");

}
È stato utile?

Soluzione

Sì, usa la funzione strtok :

char* token = strtok(msg, " ");
while (token != NULL) {
  printf("%s", token);
  token = strtok(NULL, " ");
}

Altri suggerimenti

Se vuoi leggere tutte le parole fino alla fine del file (non fermarti a newline), allora questo è più semplice:

#include <stdio.h>
int main(){
    char b[999];
    while (scanf("%s",b)==1)
        puts(b);
    return 0;
}

Il valore restituito da scanf è il numero di campi analizzati correttamente o EOF. Lo spazio bianco serve per separare "% s " campi, in modo da ottenere i token desiderati. Ovviamente, se leggi prima una riga, puoi ancora usare sscanf.

Se vuoi accumulare un array di stringhe invece di elaborarle una per una (" put (b) " sopra), allora dovrai sporcarti le mani con realloc, malloc, strcpy e strlen. I buffer di dimensioni fisse sono comunque dannosi.

C non ha stringhe nel senso in cui usi la parola. C ha matrici di caratteri.

Se vuoi un array di stringhe ... puoi avere qualcosa di simile ad un array di array di caratteri.

Ma ogni array ha una dimensione predeterminata e non puoi aggiungere più " stringhe " o renderli più lunghi dello spazio disponibile. L'altra opzione (invece delle matrici di matrici di char) è usare puntatori e memoria da malloc () e amici (lascerò la discussione su poonters, malloc () e amici per un'altra volta).

Per definire un array di array di caratteri e dividere una frase per spazi, puoi farlo

char array_of_string[10][6]; /* 10 strings of a maximum of 5 characters each, plus the NUL */
char msg[50] = "this is a test";
/* now split the msg and put the words in array_of_string */
int string_num = 0;
int word_size = 0;
int msg_index = 0;

while (msg[msg_index] != '\0') {
    if (msg[msg_index] != ' ') {
        /* add the character to the proper place in array_of_string */
        array_of_string[string_num][word_size] = msg[msg_index];
        /* and update word_size for next time through the loop */
        word_size++; /* needs check for reserved word size (5) */
    } else {
        /* a space! */
        /* first, terminate the current word */
        array_of_string[string_num][word_size] = '\0';
        /* prepare to start the next word */
        string_num++; /* needs check for reserved number of "strings" (10) */
        word_size = 0;
    }
}
/* array_of_string[0] is now "this"
 * array_of_string[1] is now "is"
 * ...
 */
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top