Generate a unique string based on a pair of string

2019-07-09 04:10发布

I've two strings StringA, StringB. I want to generate a unique string to denote this pair.

i.e.

f(x, y) should be unique for every x, y and f(x, y) = f(y, x) where x, y are strings.

Any ideas?

标签: c# string unique
9条回答
女痞
2楼-- · 2019-07-09 04:44

What about StringC = StringA + StringB;.

That is guaranteed to be unique for any combination of StringA or StringB. Or did you have some other considerations for the string also?

You can for example combine the strings and take the MD5 hash of it. Then you will get a string that is probably "unique enough" for your needs, but you cannot reverse the hash back into the strings again, but you can take the same strings and be sure that the generated hash will be the same the next time.

EDIT

I saw your edit now, but I feel it's only a matter of sorting the strings first in that case. So something like

StringC = StringA.CompareTo(StringB) < 0 ? StringA + StringB : StringB + StringA;
查看更多
手持菜刀,她持情操
3楼-- · 2019-07-09 04:49
public static String getUniqString(String x,String y){
    return (x.compareTo(y)<0)?(x+y):(y+x);
}
查看更多
虎瘦雄心在
4楼-- · 2019-07-09 04:50

Well take into consideration the first letter of each string before combining them? So if it is alphabetically ordered f(x, y) = f(y, x) will be true.

if(x > y) c = x + y; else c = y + x;

查看更多
登录 后发表回答