GRASS GIS 7 Programmer's Manual  7.0.2(2015)-r00000
token.c
Go to the documentation of this file.
1 
15 #include <stdlib.h>
16 #include <string.h>
17 #include <grass/gis.h>
18 
19 static char **tokenize(const char *, const char *, const char *);
20 
47 char **G_tokenize(const char *buf, const char *delim)
48 {
49  return tokenize(buf, delim, NULL);
50 }
51 
83 char **G_tokenize2(const char *buf, const char *delim, const char *valchar)
84 {
85  return tokenize(buf, delim, valchar);
86 }
87 
88 char **tokenize(const char *buf, const char *delim, const char *inchar)
89 {
90  int i;
91  char **tokens;
92  char *p;
93 
94  /* do not modify buf, make a copy */
95  p = G_store(buf);
96 
97  i = 0;
98  tokens = (char **)G_malloc(2 * sizeof(char *));
99 
100  /* always one token */
101  tokens[i++] = p;
102 
103  while (TRUE) {
104  /* find next delimiter */
105  while (!strchr(delim, *p)) {
106  /* opening border ? */
107  if (inchar && *p == *inchar) {
108  p++;
109  /* find closing border */
110  while (*p != *inchar && *p != 0)
111  p++;
112  if (*p == 0)
113  break;
114  }
115  p++;
116  }
117  if (*p == 0)
118  break;
119  /* replace delim with '\0' */
120  *p++ = 0;
121  /* set next token */
122  tokens[i++] = p;
123  tokens = (char **)G_realloc((char *)tokens, (i + 1) * sizeof(char *));
124  }
125  tokens[i] = NULL;
126 
127  return tokens;
128 }
129 
138 int G_number_of_tokens(char **tokens)
139 {
140  int n;
141 
142  n = 0;
143  for (n = 0; tokens[n] != NULL; n++)
144  ;
145 
146  return n;
147 }
148 
157 void G_free_tokens(char **tokens)
158 {
159  if (tokens[0] != NULL)
160  G_free(tokens[0]);
161  G_free(tokens);
162 }
char * G_store(const char *s)
Copy string to allocated memory.
Definition: strings.c:86
#define NULL
Definition: ccmath.h:32
int G_number_of_tokens(char **tokens)
Return number of tokens.
Definition: token.c:138
#define TRUE
Definition: dbfopen.c:118
void G_free_tokens(char **tokens)
Free memory allocated to tokens.
Definition: token.c:157
char ** G_tokenize2(const char *buf, const char *delim, const char *valchar)
Tokenize string.
Definition: token.c:83
char ** G_tokenize(const char *buf, const char *delim)
Tokenize string.
Definition: token.c:47
void G_free(void *buf)
Free allocated memory.
Definition: alloc.c:149