In the duplicate of this question Split char* to char * Array it is advised to use string rather than char*. But I need to work with LPWSTR. Since it's a typedef of char*, I prefer to use char*. I tried with the following code, which gives the wrong output:
char**splitByMultipleDelimiters(char*ori,char deli[],int lengthOfDelimiterArray)
{
char*copy = ori;
char** strArray = new char*[10];
int j = 0;
int offset = 0;
char*word = (char*)malloc(50);
int length;
int split = 0;
for(int i = 0; i < (int)strlen(ori); i++)
{
for(int k = 0; (k < lengthOfDelimiterArray) && (split == 0);k++)
{
if(ori[i] == deli[k])
{
split = 1;
}
}
if(split == 1)//ori[i] == deli[0]
{
length = i - offset;
strncpy(word,copy,length);
word[length] = '\0';
strArray[j] = word;
copy = ori + i + 1;
//cout << "copy: " << copy << endl;
//cout << strArray[j] << endl;
j++;
offset = i + 1;
split = 0;
}
}
strArray[j] = copy;
// string strArrayToReturn[j+1];
for(int i = 0; i < j+1; i++)
{
//strArrayToReturn[i] = strArray[i];
cout << strArray[i] << endl;
}
return strArray;
}
void main()
{
char*ori = "This:is\nmy:tst?why I hate";
char deli[] = {':','?',' ','\n'};
int lengthOfDelimiterArray = (sizeof(deli)/sizeof(*deli));
splitByMultipleDelimiters(ori,deli,lengthOfDelimiterArray);
}
Are there any other ways to split LPWSTR?