Results 1 to 3 of 3

Thread: How I do Split in C++?

  1. #1

    Thread Starter
    New Member
    Join Date
    Nov 2003
    Location
    EarthPlanet
    Posts
    2

    How I do Split in C++?

    How I do split in C++ ?

    Ex:

    test1;;test2;;test3

    How do I take those and stick those in variables ?

    In perl would be

    my($var1,$var2,$var3)=split(/;;/, $input);

    How do I do that in c++ ?

    Thanks.

  2. #2
    PowerPoster sunburnt's Avatar
    Join Date
    Feb 2001
    Location
    Boulder, Colorado
    Posts
    1,403
    Banged this out. Not sure if it's completely bug-free.

    Code:
    #include <string>
    #include <vector>
    
    std::vector<std::string> SplitStr(const std::string& text, const std::string& delimeter)
    {
       std::size_t pos = 0;
       std::size_t oldpos = 0;
       std::size_t delimlen = delimeter.length();
    
       std::vector<std::string> result;
       while(pos != std::string::npos)
       {
          pos = text.find(delimeter, oldpos);
          result.push_back(text.substr(oldpos, pos - oldpos));
          oldpos = pos + delimlen;
       }
    
       return result;
       
    }
    Usage:
    Code:
    #include <string>
    #include <vector>
    #include <iostream>
    using std::cout;
    using std::endl;
    using std::string;
    using std::vector;
    
    int main()
    {
         string s = "a_token another_token more_token last_token";
         vector<string> results = SplitStr(s, " "); // split by spaces
         for(vector<string>::iterator i = results.begin();
              i < results.end();
              ++i)
         {
              cout << (*i) << endl;
         }
    
    
         return 0;
    
    }
    I'm sure you could also use a stringstream for this. Of course, it would be much faster and efficient to use the c-style strtok.
    Every passing hour brings the Solar System forty-three thousand miles closer to Globular Cluster M13 in Hercules -- and still there are some misfits who insist that there is no such thing as progress.

  3. #3
    Frenzied Member Technocrat's Avatar
    Join Date
    Jan 2000
    Location
    I live in the 1s and 0s of everyones data streams
    Posts
    1,024
    Seems like this exact question was asked not too long ago and I think Cornedbee answered it. The boost lib already has a built in string token lib that work pretty well and is fairly easy.
    MSVS 6, .NET & .NET 2003 Pro
    I HATE MSDN with .NET & .NET 2003!!!

    Check out my sites:
    http://www.filthyhands.com
    http://www.techno-coding.com


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