简体   繁体   English

将字符串转换为特定的 int

[英]Convert string to specific int

I am creating foreground notification with ID like so: startForeground(1, notification)我正在使用 ID 创建前台通知,如下所示: startForeground(1, notification)

When initialising the service I am sending to it some string (ex: Hello).初始化服务时,我向它发送了一些字符串(例如:Hello)。 I wish that the service and notification will be bind to this string so I wish to use it as my id.我希望服务和通知将绑定到此字符串,因此我希望将其用作我的 id。 So, how can I convert string to unique ID?那么,如何将字符串转换为唯一 ID? For example the word "Hello" will always generate 123 And the word Bye will always generate 456.例如,单词“Hello”将始终生成 123 而单词 Bye 将始终生成 456。

That sounds like you want a "Hash Code";听起来你想要一个“哈希码”; a value derived from some other information that is (hopefully, but not always) unique.从其他一些信息中得出的值(希望但不总是)是唯一的。

There are a lot of different algorithms available to do this and if you search for "hash code" you will find lots of them (especially in the security domain; sha, md5 etc)有很多不同的算法可以做到这一点,如果你搜索“哈希码”,你会发现很多(尤其是在安全领域;sha、md5 等)

However, It sounds like you may not really need to get that complex (some of the more secure and "unique" hash code algorithms can be slow to calculate).但是,听起来您可能真的不需要那么复杂(一些更安全和“独特”的 hash 代码算法计算速度可能很慢)。 Is there any reason why you can't use the string itself?有什么理由不能使用字符串本身吗?

String comparison may be slow, but maybe not as slow as a good hash.字符串比较可能很慢,但可能没有好的 hash 慢。 Also you might be able to use a Hash Table if you need a faster "lookup".. hashmap如果您需要更快的“查找”,您也可以使用 Hash 表.. hashmap

Anyway, if you really do need a hash code from a string, a quick search found this (which looks reasonable) Sam Clarke;无论如何,如果你真的需要一个字符串中的 hash 代码,快速搜索会发现这个(看起来很合理) Sam Clarke; Kotlin Hash Strings Kotlin Hash 字符串

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

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