Guest User

Untitled

a guest
Jun 24th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. /*
  2. My solution to a problem posed by Ryan.
  3. I went for speed.
  4. */
  5.  
  6. #include <stdio.h>
  7. #include <ctype.h>
  8. #include <string.h>
  9. #include <assert.h>
  10.  
  11. typedef struct
  12. {
  13. const char* start;
  14. unsigned int len;
  15. unsigned int is_word;
  16. } Token;
  17.  
  18. #define MAX_TOKENS 256
  19. typedef struct
  20. {
  21. unsigned int count;
  22. unsigned int cap;
  23. Token tokens[MAX_TOKENS];
  24. } Sentence;
  25.  
  26. const char* next_token(const char* c, Token* out_token)
  27. {
  28. out_token->start = c;
  29. if (isalnum(*c))
  30. {
  31. out_token->is_word = 1;
  32. while (isalnum(*(++c)));
  33. }
  34. else if (*c)
  35. {
  36. out_token->is_word = 0;
  37. while (*c && !isalnum(*(++c)));
  38. }
  39.  
  40. // len will be 0 for failed read
  41. out_token->len = (int)(c - out_token->start);
  42. return c;
  43. }
  44.  
  45. void tokenize(Sentence* sen, const char* string)
  46. {
  47. sen->count = 0;
  48. sen->cap = 64;
  49.  
  50. const char* c = string;
  51.  
  52. while (1)
  53. {
  54. Token* out_token = sen->tokens + sen->count;
  55. c = next_token(c, out_token);
  56.  
  57. if (out_token->len == 0)
  58. {
  59. break;
  60. }
  61. else
  62. {
  63. ++sen->count;
  64. assert(sen->count < MAX_TOKENS);
  65. }
  66. }
  67. }
  68.  
  69.  
  70. void reverse(Sentence* sen)
  71. {
  72. int left = 0;
  73. int right = sen->count - 1;
  74.  
  75. // move left and right to the first words
  76. while (!sen->tokens[left].is_word && left < right) ++left;
  77. while (!sen->tokens[right].is_word && left < right) --right;
  78.  
  79. while (left < right)
  80. {
  81. // swap tokens
  82. Token temp;
  83. temp = sen->tokens[right];
  84. sen->tokens[right] = sen->tokens[left];
  85. sen->tokens[left] = temp;
  86.  
  87. // words have a one gap of punctuation between them
  88. // _A_B_C_D_
  89. left += 2;
  90. right -= 2;
  91. }
  92. }
  93.  
  94. void copy_to_string(const Sentence* sen, char* out_str)
  95. {
  96. size_t offset = 0;
  97.  
  98. for (int i = 0; i < sen->count; ++i)
  99. {
  100. memcpy(out_str + offset, sen->tokens[i].start, sen->tokens[i].len);
  101. offset += sen->tokens[i].len;
  102. }
  103. out_str[offset] = '\0';
  104. }
  105.  
  106. int main(int arg, const char* argv[])
  107. {
  108. const char* text = "Hello, how are you today? I am doing great!";
  109. char out_text[1024];
  110.  
  111. Sentence sen;
  112. tokenize(&sen, text);
  113. reverse(&sen);
  114. copy_to_string(&sen, out_text);
  115. puts(out_text);
  116. return 0;
  117. }
Add Comment
Please, Sign In to add comment