Public feed #602440

Mine

public text v1 · immutable
Raw Edit
·published 2007-07-04 02:05 UTC
rendered paste body
char **split(char *string,char delim)
{
char **a=NULL,*pch=NULL;
int element=0,i=0,z=0;

if((a=(char **)malloc(sizeof(char *)))==NULL) return NULL;

pch=strchr(string,delim);
//we do this to catch the first element
if(pch!=NULL)
	{
	a[element] =(char *) malloc(1);
	z=0;
	for(i=0;i<=(pch-string+1);i++)
		{
		if((a[element]=(char *)realloc(a[element],sizeof(char *)*(z+1)))==NULL) return NULL;
		if(string[i]==delim) { a[element][z]='\0'; break; }
		a[element][z]=string[i];
		z++;
		}
      
	element++;
	//cycle through the rest
	while (pch!=NULL)
      {
		a=(char **)realloc((char *)a,sizeof(char *) * (element+1));
		if((a[element] =(char *) malloc(1))==NULL) return NULL;
		z=0;
		for(i=(pch-string+1);i<=strlen(string);i++)
				{
				if((a[element]=(char *)realloc(a[element],sizeof(char *)*(z+1)))==NULL) return NULL;
				if(string[i]==delim) { a[element][z]='\0'; element++; break; }
				a[element][z]=string[i];
				z++;
				}
		pch=strchr(pch+1,delim);
		}
	// just allocate a little more so we can while it ok
	element++;
	if((a=(char **)realloc((char *)a,sizeof(char *) * (element+1)))==NULL) return NULL;
	a[element]=NULL;
	return (char **)a;
	}
return NULL;
}


noob

#include <string>
#include <vector>
using namespace std;

vector<string> tokenize(const string& str, const string& delimiters)
{
	vector<string> tokens;
    	string::size_type lastpos = str.find_first_not_of(delimiters, 0);
    	string::size_type pos = str.find_first_of(delimiters, lastpos);

    	while (string::npos != pos || string::npos != lastpos)
    	{
        	tokens.push_back(str.substr(lastpos, pos - lastpos));
		lastpos = str.find_first_not_of(delimiters, pos);
       	        pos = str.find_first_of(delimiters, lastpos);
    	}

	return tokens;
}