Advertisement
Guest User

Untitled

a guest
Sep 25th, 2017
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.38 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <stdbool.h>
  5.  
  6. typedef struct {
  7.     const char* text;
  8.     unsigned    text_len;
  9.     unsigned    text_pos;
  10.  
  11.     const char* token;
  12.     unsigned    token_len;
  13. } lexer_t;
  14.  
  15. bool lexer_next_token(lexer_t* self)
  16. {
  17.     unsigned i;
  18.     unsigned len;
  19.     char     ch;
  20.    
  21.     for(i = self->text_pos, len = 0;
  22.         i != self->text_len;
  23.         i++, len++) {
  24.  
  25.         ch = self->text[i];
  26.        
  27.         if((ch < 'A' || ch > 'Z') &&
  28.            (ch < 'a' || ch > 'z')) {          
  29.             if(len == 0 && ch != ' ') {
  30.                 self->token = &self->text[i];
  31.                 self->token_len = 1;
  32.                 self->text_pos = i + 1;
  33.                 return true;
  34.             }
  35.  
  36.         put_token:
  37.             self->token = &self->text[i-len];
  38.             self->token_len = len;
  39.             self->text_pos = i + 1;
  40.             return true;
  41.         }
  42.     }
  43.  
  44.     if(len) {
  45.         self->token = &self->text[i-len];
  46.         self->token_len = len;
  47.         self->text_pos = i;
  48.         return true;
  49.     }
  50.  
  51.     return false;
  52. }
  53.  
  54. int main(int argc, char* argv[])
  55. {
  56.     const char* text = "hello world";
  57.     lexer_t lexer = {0};
  58.  
  59.     lexer.text = text;
  60.     lexer.text_len = strlen(text);
  61.  
  62.     while(lexer_next_token(&lexer)) {
  63.         printf("%.*s\n",(int)lexer.token_len,lexer.token);
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement