-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtokenizer.c
51 lines (48 loc) · 1.4 KB
/
tokenizer.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <strings.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "tokenizer.h"
/*
* Ben Ellerby, CSCI 352, Summer 2016
* This function tokenizes a provided cstring according to the provided delimiters.
* Returns an array of cstrings, each element a token.
*/
char **tokenize(char *line, char *delimiters) {
char* current_token;
int token_count = 0;
char* copy1 = malloc(strlen(line));
char* copy2 = malloc(strlen(line));
memcpy(copy1, line, strlen(line));
memcpy(copy2, line, strlen(line));
current_token = strtok(copy1, delimiters);
// Traverse the string, count the tokens
while (current_token != NULL) {
token_count++;
current_token = strtok(NULL, delimiters);
}
// Allocate appropriate array size
char** tokens = malloc(sizeof(char*) * (token_count + 1));
int index = 0;
current_token = strtok(copy2, delimiters);
// Traverse the string again, copy tokens
while (current_token != NULL) {
current_token[strcspn(current_token, "\n")] = 0;
tokens[index] = current_token;
index++;
current_token = strtok(NULL, delimiters);
}
tokens[index] = '\0';
return tokens;
}
/*
* Returns the number of tokens in a provided array of tokens.
*/
int token_count(char **tokens) {
int count = 0;
int i;
for (i = 0; tokens[i]; i++) {
count++;
}
return count;
}