Basic Parsing using strtok
C string.h library provides functionalities for parsing like strtok()
string tokenizer is a functionality which will tokenize the string using the delimiter
It basically replaces the delimiter string(char *) with '\0'
next time we do strtok we give NULL as input instead of char* token with delimiter string.
char *strtok(char *token, char* delimiter);
Usage of strtok in Computer Networks for IP Address Parsing
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int val;
char c[64]="192.168.0.0"; // be careful it should be character array not character pointer
char *tok;
tok=strtok(c,".");
while(tok != NULL)
{
val = atoi(tok);
printf("%s %d %x %o\n",tok,val,val,val);
tok=strtok(NULL,".");
}
}
Wide application of strtok can be used for questions like:-
"I LOVE MY COUNTRY"
"COUNTRY MY LOVE I"
#include <bits/stdc++.h>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
void PrintReverse( stack<string> st)
{
while(!st.empty())
{
string temp = st.top();
cout << temp << " ";
st.pop();
}
}
int main()
{
stack<string> st;
char c[] = "I LOVE MY COUNTRY";
char *tok = strtok(c," ");
while(tok != NULL)
{
string str = string(tok);
st.push(str);
tok = strtok(NULL, " ");
}
PrintReverse(st);
return 0;
}
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
void PrintReverse( stack<string> st)
{
while(!st.empty())
{
string temp = st.top();
cout << temp << " ";
st.pop();
}
}
int main()
{
stack<string> st;
char c[] = "I LOVE MY COUNTRY";
char *tok = strtok(c," ");
while(tok != NULL)
{
string str = string(tok);
st.push(str);
tok = strtok(NULL, " ");
}
PrintReverse(st);
return 0;
}
Comments
Post a Comment