开发者

comparing two strings with comma separated values

开发者 https://www.devze.com 2023-03-02 23:53 出处:网络
Is there any way by which we can compare two strings having comma separates values? 开发者_开发百科

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:

  1. Split both a and b using , as a separator.
  2. Store the result in two sets (std::set for instance)
  3. Compute the difference of these two sets (for example, using std::set_difference)
  4. 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

  1. A data structure to represent a set. You may be allowed to use std::set (or multiset), or you may need to design your own.
  2. 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.
  3. 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.
  4. 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.
0

精彩评论

暂无评论...
验证码 换一张
取 消