token.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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 <string.h>
  17. #include <grass/gis.h>
  18. /**
  19. * \brief Tokenize string.
  20. *
  21. * Given a string, <b>buf</b>, turn delimiter, <b>delim</b>, into '\0'
  22. * (NULL) and place pointers to tokens in tokens. <b>buf</b> must not
  23. * contain a new line (\n). <b>delim</b> may consist of more than one
  24. * character. <i>G_free_tokens()</i> must be called when finished with
  25. * tokens to release memory.
  26. *
  27. * Example:
  28. * char **tokens;
  29. * int ntok, i;
  30. * tokens = G_tokenize(buf, " |:,");
  31. * ntok = G_number_of_tokens(tokens);
  32. * for (i=0; i < ntok; i++) {
  33. * G_debug(0, "%d=[%s]", i, tokens[i]);
  34. * }
  35. * G_free_tokens(tokens);
  36. *
  37. * \param[in] buf input string
  38. * \param[in] delim string delimiter
  39. * \return Pointer to string token
  40. */
  41. char **G_tokenize(const char *buf, const char *delim)
  42. {
  43. int i;
  44. char **tokens;
  45. char *p;
  46. i = 0;
  47. while (!strchr(delim, *buf) && (*buf == ' ' || *buf == '\t')) /* needed for G_free () */
  48. buf++;
  49. p = G_store(buf);
  50. tokens = (char **)G_malloc(sizeof(char *));
  51. while (1) {
  52. while (!strchr(delim, *p) && (*p == ' ' || *p == '\t'))
  53. p++;
  54. if (*p == 0)
  55. break;
  56. tokens[i++] = p;
  57. tokens = (char **)G_realloc((char *)tokens, (i + 1) * sizeof(char *));
  58. while (*p && (strchr(delim, *p) == NULL))
  59. p++;
  60. if (*p == 0)
  61. break;
  62. *p++ = 0;
  63. }
  64. tokens[i] = NULL;
  65. return (tokens);
  66. }
  67. /**
  68. * \brief Return number of tokens.
  69. *
  70. * <b>Note:</b> Function is incomplete.
  71. *
  72. * \param[in] tokens
  73. * \return number of tokens
  74. */
  75. int G_number_of_tokens(char **tokens)
  76. {
  77. int n;
  78. for (n = 0; tokens[n] != NULL; n++) {
  79. /* nothing */
  80. }
  81. return n;
  82. }
  83. /**
  84. * \brief Free memory allocated to tokens.
  85. *
  86. * <b>Note:</b> <i>G_free_tokens()</i> must be called when finished with
  87. * tokens to release memory.
  88. *
  89. * \param[in,out] tokens
  90. * \return
  91. */
  92. void G_free_tokens(char **tokens)
  93. {
  94. if (tokens[0] != NULL)
  95. G_free(tokens[0]);
  96. G_free(tokens);
  97. }