像比较数字一样比较字符串
我想知道是否可以像比较数字一样比较字符串。例如,有什么方法可以使 "Cat" > “狗”
I was wondering if it is possible to compare strings as if they were numbers. For instance is there any way you could make it so that "Cat" > "Dog"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您不能按照您的建议使用运算符(例如
"Cat" < "Dog"
)。正如 @larsmans 所说,这将需要 Java 不提供的运算符重载。不过,您仍然可以使用"Cat".compareTo("Dog")
比较字符串,如果字符串相等则返回 0,如果"Cat"
则返回大于 0 的数字按字典顺序小于“Dog”
,否则为负数。请参阅此页面
You can't use operators (e.g.
"Cat" < "Dog"
) as you suggest. As @larsmans says that would require operator overloading which Java doesn't provide. However, you can still compare strings using"Cat".compareTo("Dog")
which returns 0 if the strings are equal, a number greater than 0 if"Cat"
is lexicographically less than"Dog"
, or a negative number otherwise.See this page
只需实现 Comparator 接口并以您喜欢的任何方式实现比较即可。
这是 Javadoc
Just implement the Comparator interface and implement the comparison any way you like.
Here is the Javadoc
你不能。这需要 运算符重载,Java 不会让你。
You can't. This would require operator overloading, which Java won't let you.
不,不存在。
您必须使用compareTo()。
Nope, doesn't exist.
You have to use compareTo().
您可以使用
String
中的compareTo
方法You can use the
compareTo
method inString
您需要使用如下方法:
You need to use some method as below :
由于执行此操作的唯一方法是为每个单词保留一个设定值,因此您将使用数组或某种其他形式的数据存储。
这是一个示例,您只需将单词及其对应的值保留在两个数组中(注意,它们的顺序必须相同,因此第一个单词对应于第一个数字,等等)。
Since the only way to do this is to keep a set value for each word, you'd be using arrays, or some other form of data storage.
Here is an example where you just keep the words, and their corresponding values in two arrays (note, they must be in the same order, so the first word corresponds with the first number, etc).