Thread: How I do Split?

  1. #1
    Registered User
    Join Date
    Nov 2003
    Posts
    2

    How I do Split?

    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++ ?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    I never thought of it myself though I use it PHP, so I decided to write an implementation:

    Code:
    bool split(std::string sep, std::string str, std::vector<std::string> &array) {
    	int seplen = sep.length();
    	if (seplen < 1)
    		return false;
    	int len = str.length();
    	int find = 0, prev = 0;
    	for (;;) {
    		if (find = str.find(sep, find) == std::string::npos) {
    			array.push_back(str.substr(prev, len - prev));
    			return true;
    		}
    		else {
    			array.push_back(str.substr(prev, find - prev));
    			find += seplen;
    			prev = find;
    		}
    	}
    	return false;
    }
    probably could be optimised though.
    The difference would be that we would be passing a vector of strings by reference, and then accessing the elements of the vector, rather than directly assigning the values to individual variables.
    Last edited by laserlight; 11-10-2003 at 05:14 AM.

  3. #3
    It's full of stars adrianxw's Avatar
    Join Date
    Aug 2001
    Posts
    4,829
    strtok()
    Wave upon wave of demented avengers march cheerfully out of obscurity unto the dream.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. split file
    By andriss in forum C Programming
    Replies: 4
    Last Post: 10-18-2006, 03:47 PM
  2. Split line
    By groorj in forum C Programming
    Replies: 8
    Last Post: 04-24-2005, 12:05 PM
  3. Split int variable
    By Jas11 in forum C++ Programming
    Replies: 4
    Last Post: 03-28-2005, 05:06 PM
  4. CString split function ?
    By eXistenZ in forum Windows Programming
    Replies: 2
    Last Post: 02-18-2005, 10:25 AM
  5. Split function
    By fkheng in forum C Programming
    Replies: 7
    Last Post: 07-08-2003, 08:26 PM