Home > Mobile >  Is there a C method to split a one-line input?
Is there a C method to split a one-line input?

Time:10-19

I'm wondering how could I split a one-line input and use malloc() to assign a memory space to each 'element' of the input without using the <string.h> library.

CodePudding user response:

Well, the way to be able to split in an input would be the following, or at least the most successful taking into account that you want a memory space to be assigned to each "token"

#include<stdio.h>
#include <string.h>

int main() {
   char string[50] = "Hello! We are learning about strtok";
   // Extract the first token
   char * token = strtok(string, " ");
   // loop through the string to extract all other tokens
   while( token != NULL ) {
      printf( " %s\n", token ); //printing each token
      token = strtok(NULL, " ");
   }
   return 0;
}

and output well be like that:

 Hello!
 We
 are
 learning
 about
 strtok

CodePudding user response:

Would you please try something like:

#include <stdio.h>
#include <stdlib.h>
#define MAXTOK 100      // maximum number of available tokens

int
main()
{
    char str[] = "Hello! We are learning about string manipulation";

    int i, j;
    int len;            // length of each token
    char delim = ' ';   // delimiter of the tokens
    char *tok[MAXTOK];  // array for the tokens
    int n = 0;          // number of tokens

    i = 0;              // position in str[]
    while (1) {
        // increment the position until the end of string or the delimiter
        for (len = 0; str[i] != '\0' && str[i] != delim; len  ) {
            i  ;
        }
        // check the count of tokens
        if (n >= MAXTOK) {
            fprintf(stderr, "token count exceeds the array size\n");
            exit(1);
        }
        // allocate a buffer for the new token
        if (NULL == (tok[n] = malloc(len   1))) {
            fprintf(stderr, "malloc failed\n");
            exit(1);
        }
        // copy the substring
        for (j = 0; j < len; j  ) {
            tok[n][j] = str[i - len   j];
        }
        tok[n][j   1] = '\0';           // terminate with the null character
        n  ;                            // increment the token counter
        if (str[i] == '\0') break;      // end of str[]
        i  ;                            // skip the delimiter
    }

    // print the tokens
    for (j = 0; j < n; j  ) {
        printf("%s\n", tok[j]);
    }
}
  • Related