Perl join and split Equivalents in C++

實作 c++ join、split function

使用STL的string及vector類別

  • split function
    vector<string>
    split(const char* delim, string line, int max = -1) 
    {
       vector<string> tokens;
       int count = 0;
       for(;;) 
       {
          int i = line.find_first_not_of(delim);
          if(i == -1)
             break;
          
          line.erase(0, i);
          if(++count == max) 
          {
        	tokens.push_back(line);
    		break;
       	  }
       
          i = line.find_first_of(delim);
          if(i == -1) 
          {
             tokens.push_back(line);
             break;
          } else {
             string token = line.substr(0, i);
             line.erase(0, i);
             tokens.push_back(token);
          }
       } 
       return tokens;
    }
    
  • join function
    string join(string fill, vector<string> lines) {
       string line;
       for(vector<string>::iterator i = lines.begin(); i != lines.end(); i++) {
          line += fill;
          line += *i;
       } return line;
    }