Click to See Complete Forum and Search --> : string


quya
June 12th, 2002, 10:22 PM
Hi!

I have a code here which is uncompleted one, what i want to do is actually to store each string that is "two" and "three" in an array of strings so that i can use them separately later on. But i'm not sure how to do it. I can only separate them using strtok but no idea how to store them. Can somebody help me pls. Thanks!

char string[]={"two;three;"};
char *tokenPtr;

tokenPtr=strtok(string,";");

while (tokenPtr != NULL)
{
cout<<tokenPtr<<endl;
tokenPtr=strtok(NULL, ";");
}

Ungi
June 12th, 2002, 11:39 PM
char* strArr[MAX]; //Defining the Stringarray
int i;

char string[]={"two;three;"};
char *tokenPtr;

tokenPtr=strtok(string,";");

i=0;
while (tokenPtr != NULL)
{
cout<<tokenPtr<<endl;
strcpy (strArr[i], tokenPtr);
tokenPtr=strtok(NULL, ";");
i++;
}

//Display Strinarray
for (int j = 0; j < i; j++)
cout << strArr[j] << endl;

wake
June 13th, 2002, 12:15 AM
Unless you're not allowed to use the STL, why not do it with vectors/strings?
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
vector<string> myVec;

myVec.push_back("two;");
myVec.push_back("three;");
myVec.push_back("four;");

for(vector<string>::iterator myIterator = myVec.begin(); myIterator != myVec.end(); myIterator++)
cout << *myIterator << endl;

return 0;
}

Note that I haven't tested this, and Ive been up for 18 hours, so it may have some mistakes.

Regardless, its simple, safe, and efficient.

sandodo
June 13th, 2002, 03:37 AM
using the functionality of strcpy(), you can use the char "\0" as the seperator to achieve the same goal without using strtok().
Remember to add "\0" after the last string, it is used to terminate the while loop;

char buffer[100];
char str[]={"two\0three\0four\0"};
char *pstr = str;
strcpy(buffer, str);
while(buffer[0]!=NULL)
{
pstr = pstr + strlen(buffer) + 1;
strcpy(buffer, pstr);
}

quya
June 14th, 2002, 02:05 AM
THANKS FOR ALL REPLIES!