CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Dec 2009
    Posts
    161

    std::string split

    Hi,

    I am dealing with the http header. it is basically made up of pairs like
    the following:

    key: value\n\r

    Now, I need to capture those values and push them into an associative array,
    so basically I am going to use std::string this way:

    #include <string>
    #include <map>
    using namespace std;

    map<string, string> header;

    Yet, since I am quite new to std::string I'd like to know how to split one
    line based on ": ", then I am goit to remove any extra whitespaces by using
    my own chomp()

    thanks

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449

    Re: std::string split

    Do you have access to the std::string functions? There are plenty of them you can use, such as string::find_first_of() and string::substr() to get the values.

    Regards,

    Paul McKenzie

  3. #3
    Join Date
    Dec 2009
    Posts
    161

    Re: std::string split

    The thing is I don't know how to move the splitted elements into an associative hash, for example:

    Code:
    string line = "key: value\r\n";
    chomp(line);
    
    map<string,string> hash;
    
    hash.insert(make_pair((...),(...)));
    thanks

  4. #4
    Join Date
    Dec 2009
    Posts
    161

    Re: std::string split

    Ok, I sorted it out...just needed to return pair<string,string> !!

    Code:
    #include <iostream>
    #include <string>
    #include <map>
    #include <stdlib.h>
    #include <assert.h>
    using namespace std;
    
    void chomp(string&);
    pair<string,string> mysplit(string,string);
    
    int main()
    {
    	map<string,string> hash;
    
    	string line = "key: value\r\n";
    	chomp(line);
    
    	hash.insert(mysplit(line, ": "));
    
    	for(map<string,string>::const_iterator it=hash.begin(); it!=hash.end(); ++it)
    	{
    		cout << it->first << "->" << it->second << endl;
    	}
    
    	system("pause");
    	return EXIT_SUCCESS;
    }
    
    void chomp(string& szString)
    {
    	string whitespaces(" \t\f\v\n\r");
    	size_t found;
    
    	found=szString.find_last_not_of(whitespaces);
    	if (found!=string::npos)
    		szString.erase(found+1);
    	else
    		szString.clear();
    }
    
    pair<string,string> mysplit(string str, string delim)
    {
    	string::size_type match = str.find(delim);
    	assert(match != string::npos);
    
    	return pair<string,string>(
    		string(str.begin(), str.begin() + match),
    		string(str.begin() + match + delim.length(), str.end())
    		);
    }

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