|
-
June 12th, 2002, 10:22 PM
#1
string
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, ";");
}
-
June 12th, 2002, 11:39 PM
#2
Code:
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;
-
June 13th, 2002, 12:15 AM
#3
Unless you're not allowed to use the STL, why not do it with vectors/strings?
Code:
#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.
Last edited by wake; June 13th, 2002 at 12:29 AM.
-
June 13th, 2002, 03:37 AM
#4
you can also use char [] without using strtok()
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);
}
-
June 14th, 2002, 02:05 AM
#5
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|