Tokenizing a string using c /c++
Below is the code for c/c++ this a function works for me in c++. If any problem comment below.
the string str[] variable string is declared out side of function passed to function to store the tokens in the string array.remember to allocate sufficient or more space
Required parameters for function : char str[],string s[],const char t
1 parameter: str[] is the string which you wanted to tokenize.
2 parameter :s[] is string arrray used to store the token.Declare it before function passed;
3 parameter: t is char character at which the string should be tokenize();
Return value: none
look function and sample code below.
Function:
void tokenize(char str[],string s[],const char t){int i=0; string token;int j=0;int len=strlen(str); for(int i=0;i< len;i++){ if (str[i]== t ){ s[j]=token;j++;token=" "; }else{token.push_back(str[i]);} if (i==len-1){s[j]=token;} } }
sample code for testing(c++)

#include <iostream> #include <cstring> using namespace std; void tokenize(const char str[],string s[],const char t){int i=0; string token;int j=0;int len=strlen(str); for(int i=0;i<len;i++){ if (str[i]== t ){ s[j]=token;j++;token=""; }else{ token.push_back(str[i]);} if (i==len-1){s[j]=token;} } } void printA(string s[],int n){ for(int i=0;i<n;i++){ cout<<s[i]<<'\n'; }} int main(int arg,char**argv){ string str="it is a beautiful dog I have ever seen"; string s[9]; tokenize(str.c_str(),s,' '); printA(s,9); return 0;}
Output
it is a beautiful dog I have ever seen Press ENTER or type command to continue
Comments
Post a Comment