Test C


SUBMITTED BY: Guest

DATE: Oct. 14, 2012, 4:56 p.m.

FORMAT: C++

SIZE: 1.1 kB

HITS: 1395

  1. /* strtok example */
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5. int main ()
  6. {
  7. char str[] ="BLA BLA2 BLA3";
  8. char * pch;
  9. printf ("Splitting string \"%s\" into tokens:\n",str);
  10. pch = strtok (str," ");
  11. while (pch != NULL)
  12. {
  13. printf ("%s\n", pch);
  14. pch = strtok (NULL, " ");
  15. }
  16. char* strArray[50]; /* up-to 50 words can be stored */
  17. char str2[] = " Sample string!";
  18. char* p;
  19. int i = 0;
  20. p = strtok(str2, " ,.?!");
  21. while (p)
  22. {
  23. strArray[i] = malloc(strlen(p) + 1);
  24. strcpy(strArray[i++], p);
  25. printf("Extracted string part to element %i: %s\n", i, p);
  26. p = strtok(NULL, " ,.?!");
  27. }
  28. int j;
  29. for (j = i + 1; j <= 50; j++) {
  30. /* Initialize the rest. */
  31. printf("Finishing init of element %i\n", j);
  32. strArray[i] = malloc(1);
  33. //strcpy(strArray[i], NULL);
  34. }
  35. for (i = 0; i < 50; i++)
  36. {
  37. if (strArray[i]) { /* check for null data */
  38. printf("String part, element %i: %s\n", i, strArray[i]);
  39. }
  40. }
  41. return 0;
  42. }

comments powered by Disqus