CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Thread: string

  1. #1
    Join Date
    Apr 2002
    Posts
    17

    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, ";");
    }

  2. #2
    Join Date
    Apr 2002
    Posts
    388
    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;

  3. #3
    Join Date
    Jun 2002
    Location
    Florida
    Posts
    32
    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.

  4. #4
    Join Date
    Jun 2002
    Posts
    137

    Talking 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);
    }

  5. #5
    Join Date
    Apr 2002
    Posts
    17
    THANKS FOR ALL REPLIES!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured