简体   繁体   English

将字符串转换为 2 个数字之间的唯一 ID

[英]Turn string to unique id between 2 numbers

How would you convert a string to a unique integer between two values?如何将字符串转换为两个值之间的唯一整数? In a way that it would always return the same number for the same string以某种方式始终为相同的字符串返回相同的数字

For example if i had this string "Hello world" it would need to be converted to an unique number between 0 and 15. And then if the string was different it would be converted to a different number between 0 and 15 but the same string would always convert to the same number例如,如果我有这个字符串“Hello world”,它需要转换为 0 到 15 之间的唯一数字。然后如果字符串不同,它将转换为 0 到 15 之间的不同数字,但相同的字符串会始终转换为相同的数字

You can get the hash code which is just an integer from a string in java with string.hashCode().您可以使用 string.hashCode() 从 java 中的字符串获取哈希码,它只是一个整数。 Maybe that could be used to generate it somehow.也许这可以用来以某种方式生成它。

string.hashCode() % 15; would get you a number in [0, 14].会给你一个 [0, 14] 中的数字。 If 15 needs to be an option, then you could do string.hashCode() % 16;如果 15 需要是一个选项,那么您可以执行string.hashCode() % 16; instead.反而。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM