bail3yz
asked on
How can I edit this string in C++?
Hi,
I have some data in a string.. and I need to extract pieces of it.
The string has this info in it
"The cost: $150 (Total)"
I need to get 150 out of the string.. I dont need any of the other info.. how can I do this?
Also.. originally the data is in a char*, so if we can do it somehow with a char* that works too
Thanks
I have some data in a string.. and I need to extract pieces of it.
The string has this info in it
"The cost: $150 (Total)"
I need to get 150 out of the string.. I dont need any of the other info.. how can I do this?
Also.. originally the data is in a char*, so if we can do it somehow with a char* that works too
Thanks
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
>> find that start and end index of the number
Heh, I forgot to point out you then use substr and stringstream to convert the string representation to a integer one =/
http://www.cplusplus.com/reference/string/string/substr/
http://www.cplusplus.com/reference/iostream/stringstream/
Heh, I forgot to point out you then use substr and stringstream to convert the string representation to a integer one =/
http://www.cplusplus.com/reference/string/string/substr/
http://www.cplusplus.com/reference/iostream/stringstream/
ASKER
Hi evilrix,
I actually ended up using just find (which I didnt know about until your post!) and substr.. because the # is always different but the rest of the text is always the same..
Thanks for the help!
I actually ended up using just find (which I didnt know about until your post!) and substr.. because the # is always different but the rest of the text is always the same..
Thanks for the help!
If the rest of the string is always the same (guaranteed), you can simply do :
const char* str = "The cost: $150 (Total)";
int cost = atoi(str + strlen("The cost: $"));
const char* str = "The cost: $150 (Total)";
int cost = atoi(str + strlen("The cost: $"));
Or if you want to avoid the strlen call :
int cost = atoi(str + 11));
int cost = atoi(str + 11));
int Value;
if (sscanf ("The cost: $150 (Total)", "[^0-9]%d", &Value) > 0)
// Value was extracted.
Good Luck,
Kent