以下实例中我们通过字符串函数 compareTo (string) ,compareToIgnoreCase(String) 及 compareTo(object string) 来比较两个字符串,并返回字符串中第一个字母ASCII的差值。
package Java_Learn.File; public class StringCompareEmp { public static void main(String[] args) { String str = "Hello World"; String anotherString = "hello world"; Object objStr = str; System.out.println(str.compareTo(anotherString)); System.out.println(str.compareToIgnoreCase(anotherString)); System.out.println(str.compareTo(objStr.toString())); } }
结果:
"C:Program FilesJavajdk1.8.0_221injava.exe" "-javaagent:C:Program FilesJetBrainsIntelliJ IDEA 2019.3.3libidea_rt.jar=49198:C:Program FilesJetBrainsIntelliJ IDEA 2019.3.3in" -Dfile.encoding=UTF-8 -classpath "C:Program FilesJavajdk1.8.0_221jrelibcharsets.jar;C:Program FilesJavajdk1.8.0_221jrelibdeploy.jar;C:Program FilesJavajdk1.8.0_221jrelibextaccess-bridge-64.jar;C:Program FilesJavajdk1.8.0_221jrelibextcldrdata.jar;C:Program FilesJavajdk1.8.0_221jrelibextdnsns.jar;C:Program FilesJavajdk1.8.0_221jrelibextjaccess.jar;C:Program FilesJavajdk1.8.0_221jrelibextjfxrt.jar;C:Program FilesJavajdk1.8.0_221jrelibextlocaledata.jar;C:Program FilesJavajdk1.8.0_221jrelibext ashorn.jar;C:Program FilesJavajdk1.8.0_221jrelibextsunec.jar;C:Program FilesJavajdk1.8.0_221jrelibextsunjce_provider.jar;C:Program FilesJavajdk1.8.0_221jrelibextsunmscapi.jar;C:Program FilesJavajdk1.8.0_221jrelibextsunpkcs11.jar;C:Program FilesJavajdk1.8.0_221jrelibextzipfs.jar;C:Program FilesJavajdk1.8.0_221jrelibjavaws.jar;C:Program FilesJavajdk1.8.0_221jrelibjce.jar;C:Program FilesJavajdk1.8.0_221jrelibjfr.jar;C:Program FilesJavajdk1.8.0_221jrelibjfxswt.jar;C:Program FilesJavajdk1.8.0_221jrelibjsse.jar;C:Program FilesJavajdk1.8.0_221jrelibmanagement-agent.jar;C:Program FilesJavajdk1.8.0_221jrelibplugin.jar;C:Program FilesJavajdk1.8.0_221jrelib esources.jar;C:Program FilesJavajdk1.8.0_221jrelib t.jar;C:appWorkSpace argetclasses;C:Program Files (x86)scalalibscala-actors-2.11.0.jar;C:Program Files (x86)scalalibscala-actors-migration_2.11-1.1.0.jar;C:Program Files (x86)scalalibscala-library.jar;C:Program Files (x86)scalalibscala-parser-combinators_2.11-1.0.1.jar;C:Program Files (x86)scalalibscala-reflect.jar;C:Program Files (x86)scalalibscala-swing_2.11-1.0.1.jar;C:Program Files (x86)scalalibscala-xml_2.11-1.0.1.jar;C: epositoryorgscala-langscala-library2.11.0scala-library-2.11.0.jar" Java_Learn.File.StringCompareEmp -32 0 0 Process finished with exit code 0