Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Cutting strings 1

Status
Not open for further replies.

lixi

Technical User
Jan 19, 2005
2
AT
Hi!

Can please anybody tell me the best way for cutting this string

16/12/2004 14:02:48,"C:\Chqtest\MICRTestBatch$C000056C99D0250A10000055C09$_A.tif","C000056C99D0250A10000055C09"

As output I want to have "C000056C99D0250A10000055C09" (so the string after the second ",")
Can sobebody tell me which function to use in Visual C++?

In addition to that I want to pick out only the numeric values of my string: 000056
99
0250
100000
09 (I want to have 5 substrings)

Thanks in advance for your help
Andrea
 
Try use this improvisational tokenizer:
Code:
class CSV
{
public:
	CSV(int sep = ','):comma(sep) {}
	CSV(const string& str, int sep=','):comma(sep) { parse(str); }
	int parse(const string& str);
	int parse(const char* pstr); 
	void clear() { token.clear(); }
	int	size() const { return token.size(); }
	string& operator [](int i) { return token[i]; };
	const string& operator[](int i) const 
	{ 
		return i >= 0 && i < size()?token[i]:nullstr; 
	}
protected:
	vector<string> token;
	char comma;
private:
	static string nullstr;
};

string CSV::nullstr;

namespace {
string& dequote(string& s)
{
	int	pos;
	if (s[0] == '\"')
		s.erase(0,1);// = s.substr(1);
	if ((pos=s.length()-1) >= 0 && s[pos] == '\"')
		s.erase(pos,1);
	return s;
}
};

int CSV::parse(const string& str)
{
	string::size_type npos, pos = 0;
	string s;

	clear();
	while ((npos=str.find_first_of(comma,pos)) != string::npos)
	{
		s = str.substr(pos,npos-pos);
		token.push_back(dequote(s));
		pos = npos+1;
	}
	s = str.substr(pos);
	token.push_back(dequote(s));
	return size();
}

int CSV::parse(const char* pstr)
{
	if (pstr)
	{
		string s(pstr);
		return parse(s);
	}
	else
	{
		clear();
		return 0;
	}
}
Now load a string into this class object:
Code:
CSV csv("11111,22222,\"quoted\"");
// or CSV csv; ... csv.parse(thestring); ...
// Get the 3rd token [i]quoted[/i] as csv[2]...
You may improve this tokenizer to solve the 2nd problem.
Use find_first_of("0123456789"...) and find_first_not_of(digits,...) std::string class member fumction to separate numbers from the string.
Sorry, I have no time now to invent this code...
Good luck!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top