如何比较java中的两个字符串并按字母顺序定义哪个字符串小于另一个字符串? [英] How can I compare two strings in java and define which of them is smaller than the other alphabetically?

查看:949
本文介绍了如何比较java中的两个字符串并按字母顺序定义哪个字符串小于另一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用二进制搜索算法来搜索用户在一个非常大的排序文件中输入的字符串。我无法将用户输入的字符串与位于文件中间行的字符串进行比较以继续我的二进制搜索。

I want to use the binary search algorithm to search the string which has been entered by the user in a very big sorted file. I can not compare the string which has been entered by the user with the string which has been located in the middle line of the file to continue my binary search.

例如,如果用户的字符串是 abcda ,并且文件的字符串是 abcza ,很明显用户的字符串小于文件的字符串。它是如何在java中实现的?如果你可以帮我提供示例代码,那将会很棒。

For example, if the user's string is abcda and the file's string is abcza, it is obvious that the user's string is smaller than the file's string. How is it implemented in java? it will be great if you can help me with a sample code.

推荐答案

你可以使用

str1.compareTo(str2);

如果 str1 按字典顺序小于 str2 将返回负数 0 如果相等或正数如果 str1 更大。

If str1 is lexicographically less than str2, a negative number will be returned, 0 if equal or a positive number if str1 is greater.

例如,

"a".compareTo("b"); // returns a negative number, here -1
"a".compareTo("a"); // returns  0
"b".compareTo("a"); // returns a positive number, here 1

这篇关于如何比较java中的两个字符串并按字母顺序定义哪个字符串小于另一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆