Reputation: 299
I'm trying to parse this line
Completion_Time_Stamp = 2013-04-04@12:10:22(Eastern Daylight Time)
and put the name in one variable and value in another
token[0] = strtok(buf, " = "); // first token
if (token[0]) // zero if line is blank
{
for (n = 1; n < 10; n++)
{
token[n] = strtok(0, " = "); // subsequent tokens
if (!token[n]) break; // no more tokens
}
}
Output :
token[0] = Completion_Time_Stamp
token[1] = 2013-04-04@12:10:22(Eastern
token[2] = Daylight
token[3] = Time)
But I want something like this :
token[0] = Completion_Time_Stamp
token[1] = 2013-04-04@12:10:22(Eastern Daylight Time)
How do I achieve this ? Mutiple delimiters ??
Upvotes: 1
Views: 791
Reputation: 23634
Use std::string, find with arguments "=", then using substring to get those 2 strings.
std::string str1 ="Completion_Time_Stamp = 2013-04-04@12:10:22(Eastern Daylight Time)";
std::string str2 = "=";
std::string part1="";
std::string part2="";
unsigned found = str1.find(str2);
if (found!=std::string::npos)
{
part1 = str1.substr(0,found-1);
part2 = str1.substr(found+2);
}
cout << part1 << "\n" << part2 <<endl;
I got the following:
Completion_Time_Stamp//^^no space here and beginning of second part
2013-04-04@12:10:22(Eastern Daylight Time)
Upvotes: 0
Reputation: 2272
You should use just =
as your delimiter, and then right trim and left trim your results to get rid of the trailing right space on token 0 and left space on token 1.
Upvotes: 1
Reputation: 409186
Why not use the functionality that already exists in std::string
, like using find
and substr
.
Something like:
std::string str = "Completion_Time_Stamp = 2013-04-04@12:10:22(Eastern Daylight Time)";
auto delim_pos = str.find('=');
std::string keyword = str.substr(0, delim_pos);
std::string data = str.substr(delim_pos);
Note: The delimiter position (delim_pos
in my example) may have to be adjusted when making the substrings.
Upvotes: 4