token.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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).
  23. *
  24. * \param[in] buf input string
  25. * \param[in] delim string delimiter
  26. * \return Pointer to string token
  27. */
  28. char **G_tokenize(const char *buf, const char *delim)
  29. {
  30. int i;
  31. char **tokens;
  32. char *p;
  33. i = 0;
  34. while (!G_index(delim, *buf) && (*buf == ' ' || *buf == '\t')) /* needed for G_free () */
  35. buf++;
  36. p = G_store(buf);
  37. tokens = (char **)G_malloc(sizeof(char *));
  38. while (1) {
  39. while (!G_index(delim, *p) && (*p == ' ' || *p == '\t'))
  40. p++;
  41. if (*p == 0)
  42. break;
  43. tokens[i++] = p;
  44. tokens = (char **)G_realloc((char *)tokens, (i + 1) * sizeof(char *));
  45. while (*p && (G_index(delim, *p) == NULL))
  46. p++;
  47. if (*p == 0)
  48. break;
  49. *p++ = 0;
  50. }
  51. tokens[i] = NULL;
  52. return (tokens);
  53. }
  54. /**
  55. * \brief Return number of tokens.
  56. *
  57. * <b>Note:</b> Function is incomplete.
  58. *
  59. * \param[in] tokens
  60. * \return number of tokens
  61. */
  62. int G_number_of_tokens(char **tokens)
  63. {
  64. int n;
  65. for (n = 0; tokens[n] != NULL; n++) {
  66. /* nothing */
  67. }
  68. return n;
  69. }
  70. /**
  71. * \brief Free memory allocated to tokens.
  72. *
  73. * <b>Note:</b> <i>G_free_tokens()</i> must be called when finished with
  74. * tokens to release memory.
  75. *
  76. * \param[in,out] tokens
  77. * \return
  78. */
  79. void G_free_tokens(char **tokens)
  80. {
  81. if (tokens[0] != NULL)
  82. G_free(tokens[0]);
  83. G_free(tokens);
  84. }