Is there any way by which we can compare two strings having comma separates values?
开发者_开发百科To make it clear:
string S1 = "a,b,c,d,e"
string S2 = "c,d"
string S3 = "a,b,e" //where string S3 is got by subtracting S2 from S1 (S1 - S2)
Is it possible to do this with some function?
If I got what you want right, you want to get the elements that are not in both strings.
Here's how I would do it:
- Split both a and b using
,
as a separator. - Store the result in two sets (
std::set
for instance) - Compute the difference of these two sets (for example, using
std::set_difference
) - Convert the resulting set to a string by gluing each element together using
,
I'm guessing this is a homework assignment, so you won't get any code from me.
If I understand the question, you're talking about the "set difference", not a comparision; that is, finding the elements of one set that are not in another. To do this, you'd need
- A data structure to represent a set. You may be allowed to use
std::set
(ormultiset
), or you may need to design your own. - A function, or constructor, to read the values from a string, looking for commas that separate them. If you're allowed to use libraries, then
std::stringstream
might be useful. - A function to calculate the difference between two sets (either by removing one set from the other, or creating a new set with the correct members). Again, if you can use the library, have a look at
std::set_difference
. - A function to convert the set into a string (the inverse of the function in 2) to give the final result. As in 2,
std::stringstream
would be useful.
精彩评论