Use strtok( ) to tokenize a null-terminated string: - C++ Data Type

C++ examples for Data Type:char array

Description

Use strtok( ) to tokenize a null-terminated string:

Demo Code

#include <iostream>
#include <cstring>
using namespace std;
int main() {/*  w  w  w.  jav  a2  s.  c  o  m*/
   // First, use strtok() to tokenize a sentence.
   char delims[] = "., ?;!";
   char str[] = "I like apples, pears, and grapes. Do you? this is a test";
   char *tok;
   cout << "Obtain the words in a sentence.\n";

   // Pass the string to be tokenized and get the first token.
   tok = strtok(str, delims);

   // Get all remaining tokens.
   while(tok) {
      cout << tok << endl;
      // Each subsequent call to strtok() is passed NULL for the first argument.
      tok  = strtok(NULL, delims);
   }

   // use strtok() to extract keys and values stored in key/value pairs within a string.

   char kvpairs[] = "count=10, name=\"abc, jr.\", max=100, min=0.01";

   // Create a list of delimiters for key/value pairs.
   char kvdelims[] = " =,";
   cout << "\nTokenize key/value pairs.\n";

   // Get the first key.
   tok = strtok(kvpairs, kvdelims);

   // Get all remaining tokens.
   while(tok) {
      cout << "Key: " << tok << " ";
      if(!strcmp("name", tok)) {
         tok = strtok(NULL, "\"");
      }
      else {
         tok  = strtok(NULL, kvdelims);
      }
      cout << "Value: " << tok << endl;
      // Get the next key.
      tok = strtok(NULL, kvdelims);
   }
   return 0;
}

Result


Related Tutorials