(续)字符串比较compareTo (Object object)String sl = new String("welcome") ;String s2 = "welcome";if(sl.compareTo (s2) > 0)sl is greater than s2elseif(sl.compareTo(s2)0/ /s1and s2 have the samecontentselse// sl is lesss than s2Liang,Introduction toJava Programming.EighthEdition,(c)2011Pearson Education,Inc.All16rightsreserved.0132130807
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 16 字符串比较(续) compareTo(Object object) String s1 = new String("Welcome“); String s2 = "welcome"; if (s1.compareTo(s2) > 0) { // s1 is greater than s2 } else if (s1.compareTo(s2) == 0) { // s1 and s2 have the same contents } else // s1 is less than s2
字符串长度、字符以及组合字符串java.lang.String返回这个字符串的字符个数+length(O): int返回这个字符串的指定下标处的字符+charAt(index:int):char返回连接这个字符串和字符串s1所构成的新字符串+concat(sl: String): StringLiang,Introduction toJava Programming,EighthEdition,(c)2011Pearson Education,Inc.All17rightsreserved.0132130807
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 17 字符串长度、字符 以及组合字符串 java.lang.String +length(): int +charAt(index: int): char +concat(s1: String): String 返回这个字符串的字符个数 返回这个字符串的指定下标处的字符 返回连接这个字符串和字符串 s1 所构成的新字符串
获取字符串长度使用length()方法获取字符串的长度:"welcome"二message(返回7)message.length()Liang,Introduction toJava Programming,EighthEdition,(c)2011Pearson Education,Inc.All18rightsreserved.0132130807
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 18 获取字符串长度 使用length()方法获取字符串的长度: message = "Welcome"; message.length() (返回7)
在字符串中获取单个字符不能使用message[]使用message.charAt(index)下标index从O开始89下标03561041421111213JW1t信息ec0eaa0mV不不message.charAt(O)message.lengthO is 15message.charAt(14)Liang.Introduction to JavaProgramming.EighthEdition,(c)2011Pearson Education,Inc.All19rightsreserved.0132130807
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 19 在字符串中获取单个字符 不能使用message[0] 使用message.charAt(index) 下标index从0开始 W e l c o m e t o J a v a 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 信息 下标 message.charAt(0) message.length() is 15 message.charAt(14)
字符串连接s3String s1.concat (s2) 二String s3 = sl + s2:s1 + s2 + s3 + s4 + s5 等价于(((s1 .concat(s2)).concat(s3)).concat(s4).concat(s5)Liang,Introduction toJava Programming,EighthEdition,(c)2011Pearson Education,Inc.All20rightsreserved.0132130807
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 20 字符串连接 String s3 = s1.concat(s2); String s3 = s1 + s2; s1 + s2 + s3 + s4 + s5 等价于 (((s1.concat(s2)).concat(s3)).concat(s4)).concat(s5);