token.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. /**
  2. * \file token.c
  3. *
  4. * \brief GIS Library - Token functions.
  5. *
  6. * (C) 2001-2008 by the GRASS Development Team
  7. *
  8. * This program is free software under the GNU General Public License
  9. * (>=v2). Read the file COPYING that comes with GRASS for details.
  10. *
  11. * \author GRASS GIS Development Team
  12. *
  13. * \date 1999-2008
  14. */
  15. #include <stdlib.h>
  16. #include <grass/gis.h>
  17. /**
  18. * \brief Tokenize string.
  19. *
  20. * Given a string, <b>buf</b>, turn delimiter, <b>delim</b>, into '\0'
  21. * (NULL) and place pointers to tokens in tokens. <b>buf</b> must not
  22. * contain a new line (\n). <b>delim</b> may consist of more than one
  23. * character. <i>G_free_tokens()</i> must be called when finished with
  24. * tokens to release memory.
  25. *
  26. * Example:
  27. * char **tokens;
  28. * int ntok, i;
  29. * tokens = G_tokenize(buf, " |:,");
  30. * ntok = G_number_of_tokens(tokens);
  31. * for (i=0; i < ntok; i++) {
  32. * G_debug(0, "%d=[%s]", i, tokens[i]);
  33. * }
  34. * G_free_tokens(tokens);
  35. *
  36. * \param[in] buf input string
  37. * \param[in] delim string delimiter
  38. * \return Pointer to string token
  39. */
  40. char **G_tokenize(const char *buf, const char *delim)
  41. {
  42. int i;
  43. char **tokens;
  44. char *p;
  45. i = 0;
  46. while (!G_index(delim, *buf) && (*buf == ' ' || *buf == '\t')) /* needed for G_free () */
  47. buf++;
  48. p = G_store(buf);
  49. tokens = (char **)G_malloc(sizeof(char *));
  50. while (1) {
  51. while (!G_index(delim, *p) && (*p == ' ' || *p == '\t'))
  52. p++;
  53. if (*p == 0)
  54. break;
  55. tokens[i++] = p;
  56. tokens = (char **)G_realloc((char *)tokens, (i + 1) * sizeof(char *));
  57. while (*p && (G_index(delim, *p) == NULL))
  58. p++;
  59. if (*p == 0)
  60. break;
  61. *p++ = 0;
  62. }
  63. tokens[i] = NULL;
  64. return (tokens);
  65. }
  66. /**
  67. * \brief Return number of tokens.
  68. *
  69. * <b>Note:</b> Function is incomplete.
  70. *
  71. * \param[in] tokens
  72. * \return number of tokens
  73. */
  74. int G_number_of_tokens(char **tokens)
  75. {
  76. int n;
  77. for (n = 0; tokens[n] != NULL; n++) {
  78. /* nothing */
  79. }
  80. return n;
  81. }
  82. /**
  83. * \brief Free memory allocated to tokens.
  84. *
  85. * <b>Note:</b> <i>G_free_tokens()</i> must be called when finished with
  86. * tokens to release memory.
  87. *
  88. * \param[in,out] tokens
  89. * \return
  90. */
  91. void G_free_tokens(char **tokens)
  92. {
  93. if (tokens[0] != NULL)
  94. G_free(tokens[0]);
  95. G_free(tokens);
  96. }