Skip to content

Instantly share code, notes, and snippets.

@dharanad
Last active June 16, 2020 10:08
Show Gist options
  • Save dharanad/acc8dad6d2676bfdad547cabb9f904c2 to your computer and use it in GitHub Desktop.
Save dharanad/acc8dad6d2676bfdad547cabb9f904c2 to your computer and use it in GitHub Desktop.
C++ String Tokenising
#include <iostream>
#include <cstring>
using namespace std;
vector<string> split(string str,const char *delim){
// Convert from char * to char
char *cexp = new char[str.length() + 1]; // 1 extra char of null terminated character
strcpy(cexp, str.c_str());
// Tokenise character array
char *tok = strtok(cexp, delim);
vector<string> tokens;
while(tok != NULL){
tokens.push_back(string(tok));
tok = strtok(NULL, delim);
}
delete[] cexp;
return tokens;
}
char* mystrtoken(char *s, char delim){
static char *input = NULL;
if(s != NULL){
input = s;
}
if(input == NULL){
return NULL;
}
char *output = new char[strlen(input) + 1];
int i = 0;
for(; input[i] != '\0'; i++){
if(input[i] != delim){
output[i] = input[i];
}else{
input = input + i + 1; // update input
output[i] = '\0';
return output;
}
}
output[i] = '\0';
input = NULL;
return output;
}
int main() {
// String Tokenising
char s[100] = "Today is a rainy day";
char *tokenPtr = strtok(s," ");
while(tokenPtr != NULL){
cout << tokenPtr << "\n";
tokenPtr = strtok(NULL, " "); // we are passing null so that this function points to previously passed string
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment