JAVA培训教材(2)
2802 点击·0 回帖
![]() | ![]() | |
![]() | 2.字符串的常用方法 1)public int length() 使用String类中的length()方法可以获取一个字符串的长度,如 String s="we are student",tom="我们是学生"; int n1,n2,n3; n1=s.length(); //n1的值是15 n2=tom.length(); //n2的值是5. n3="we are student=我们是学生".length();// n3的值是21 2)public boolean equals(String s) 字符串对象调用String类中的equals方法,比较当前字符串对象的实体是否与参数指定的字符串s的实体相同,如: String tom=new String("we are student"); String boy=new String("We are students"); String jerry=new String(tom); 则:tom.equals(boy)或tom.equals(jerry) 的值都是true 因为比较是是实体,即字符串本身(各个位置的字符与长度是否相同) 注意:如果是tom==jerry或tome==boy 的值就是false,因为new了之后,字符串就是对象,tom,boy,jerry是值(地址),因为每个对象在创建后都有自己的内存空间,所以用"=="比较当然会不同喽 字符串对象调用public boolean equalsIgnoreCase(String s) 比较当前字符串对象与参数指定的字符串s是否相同,比较时候忽略大小写. 仔细体会下面的例子: 复制代码 class E { public static void main(String args[]) { String s1,s2; s1=new String("we are students"); s2=new String("we are students"); System.out.println(s1.equals(s2));//字符串实体相同,输出结果是true System.out.println(s1==s2); //对象各自分配的空间不同,输出结果为false String s3,s4; s3="how are you"; s4="how are you"; System.out.println(s3.equals(s4)); //同一个空间,结果为true System.out.println(s3==s4); //同一个空间,结果为true } } 3)public boolean startsWith(String s) 和public boolean endWith(String s) 字符串对象调用startsWith(String s)方法,判断当前字符串对象的 前缀 是否是参数指定的字符串s,如 String tom="bbs.bc-cn.net",jerry="www.bc-cn.net"; tom.startsWith("bbs")的值是true jerry.startsWith("bbs")的值是false 同样,endWith(String s)判断的就是后缀 字符串对象调用public boolean startsWith(String prefix,int toffset)方法,判断当前字符串从toffset索引处开始的前缀是否是参数指定的字符串prefix,如: String str="123456"; boolean boo=str.startsWith("456",3)// 很容易看出来,boo的值应该是true 4)public boolean regionMatches(int firstStart,String other,int otherStart,int length) 字符串调用此方法,从当前字符串参数firstStart指定的位置开始处,取长度为length的一个子串,并将这个子串和参数other指定的一个子串进行比较.其中,other指定的字符串是从参数otherStart指定的位置开始,从other中取长度为length的一个子串.如果两个子串相同则该方法返回true | |
![]() | ![]() |