Advertisement
salmancreation

String to Token C - Complier Desgin

Sep 23rd, 2017
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.64 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. int main(){
  4.     char str[100] = "This is sample sentence";
  5.  
  6.     const char s[2] = " ";
  7.     char* token;
  8.  
  9.     token = strtok(str, s);
  10.  
  11.     while(token != NULL){
  12.  
  13.         printf("%s\n", token);
  14.  
  15.         token = strtok(NULL, s);
  16.  
  17.     }
  18.     return 0;
  19.  
  20. }
  21.  
  22.  
  23. -------------------- with out strtok ------------
  24.  
  25. #include <stdio.h>
  26. #include <stdbool.h>
  27. #include <ctype.h>
  28.  
  29. static bool readLine (const char* data, const char** beginPtr, const char** endPtr) {
  30.     static const char* nextStart;
  31.     if (data) {
  32.         nextStart = data;
  33.         return true;
  34.     }
  35.     if (*nextStart == '\0') return false;
  36.     *beginPtr = nextStart;
  37.  
  38.     // Find next delimiter.
  39.     do {
  40.         nextStart++;
  41.     } while (*nextStart != '\0' && *nextStart != ' ');
  42.  
  43.     // Trim whitespace.
  44.     *endPtr = nextStart - 1;
  45.     while (isspace(**beginPtr) && *beginPtr < *endPtr)
  46.         (*beginPtr)++;
  47.     while (isspace(**endPtr) && *endPtr >= *beginPtr)
  48.         (*endPtr)--;
  49.     (*endPtr)++;
  50.  
  51.     return true;
  52. }
  53.  
  54. int main (void) {
  55.     const char* data = "This is sample sentence";
  56.     const char* begin;
  57.     const char* end;
  58.     readLine(data, 0, 0);
  59.     while (readLine(0, &begin, &end)) {
  60.         printf("%.*s\n", end - begin, begin);
  61.     }
  62.     return 0;
  63. }
  64.  
  65.  
  66. ----------------- Delimiting-------------
  67.  
  68. #include <stdio.h>
  69. #include <string.h>
  70.  
  71. int main ()
  72. {
  73.   char str[] ="- This, a sample string.";
  74.   char * pch;
  75.   printf ("Splitting string \"%s\" into tokens:\n",str);
  76.   pch = strtok (str," ,.-");
  77.   while (pch != NULL)
  78.   {
  79.     printf ("%s\n",pch);
  80.     pch = strtok (NULL, " ,.-");
  81.   }
  82.   return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement