首页 > 编程知识 正文

java string比较大小,java字符串怎么比较大小

时间:2023-05-06 04:27:36 阅读:151250 作者:791

注:这篇博文当时有点问题,今天(2020-02-13 )被修改了。 但是,文章的摘要还是修改前的内容,我来说明。

代码如下:

import java.util.Scanner; /**Java how to program, 10 thedition * 14.3 (comparing strings ) writeanapplicationthatusesstringmethodcompareto * tocomparetwostringsinputbytheuser . lessthan,equaltoorgreaterthanthesecond.* @ authorpandenghuang @ 163.com */public class compare to { publicstaticvoicvoidmain String s1=input.nextLine (; 请输入System.out.print ('字符串2:' ); String s2=input.nextLine (; intresult=S1.comPareto(S2; if(result0) System.out.printf (字符串1-%s为字符串2-%s%n ),s1,s2 ); elseif(result0) System.out.printf (字符串1-%s为字符串2-%s%n ),s1,s2 ); else System.out.printf (比较结果:字符串1-%s为字符串2-%s%n ),s1,s2 ); }

运行结果:

字符串1 :请输入海

字符串2 :请输入斌

字符串1-海大于字符串2-斌

附件:

JavaDoc中的compareTo方法的说明如下。

int Java.lang.string.com Pareto (stringanotherstring ) )。

comparestwostringslexicographically.thecomparisonisbasedontheunicodevalueofeachcharacterinthestrings.thecharactersersequencer scomparedlexicographicallytothecharactersequencerepresentedbytheargumentstring.theresultisanegativeintegative thistringongobjective theargumentstring.theresultisapositiveintegerifthisstringobjectlexicographicallyfolliy argumentstring.theresultiszeroifthesthestring compare to returns0exactlywhentheequals (对象) method would returntrue。

thisisthedefinitionoflexicographicordering.iftwostringsaredifferent,theneitheyhavedifferentcharactersatsomeindexthatisisting or their lengths are different,orboth.iftheyhavedifferentcharactersatoneormoreindexpositions,let k be the smallest such index; thenthestringwhosecharacteratpositionkhasthesmallervalue,as determined by using the operator,lexicographicallyprecedestheotherstherstheratother comparetoreturnsthedifferenceofthetwocharactervaluesatpositionkinthetwo

this.Charat(k )-anotherString.charAt(k ) k ) )。

ifthereisnoindexpositionatwhichtheydiffer,thentheshorterstringlexicographicallyprecedesthelongerstring.in this case,compart

this.length (-anotherstring.length ) (Specified by:compareTo )…) in Comparable Parameters:

33558 www.Sina.com/thestringtobecompared。

Returns:

the value0iftheargumentstringisequaltothisstring; A valueless than0ifthisstringislexicographicallylessthanthestringargument; andavaluegreaterthan0ifthisstringislexicographicallygreaterthanthestringargument。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。