1 package cn.zhang.Array; 2 /** 3 * String类的一些常用方法 4 * @author 张涛 5 * 6 */ 7 public class TestString 8 { 9 public static void main(String[] args) 10 { 11 String s1 = "abcdef"; 12 String s2 = "123456"; 13 String s3 = "abcdef"; 14 String s4 = new String("abcdef"); 15 String s5 = "ABCDEF"; 16 17 /** 18 * 方法一 :char charAt(int index) 19 * 功能:可返回任意索引处的字符 20 */ 21 System.out.println(s1.charAt(5)); 22 System.out.println(s2.charAt(5)); 23 24 /** 25 * 方法二:boolean equals(Object obj) 26 * 功能:判断两个字符串是否相同,注意String中的equals方法此时已经重写了父类Object中的equals方法 27 * 28 * 31-32行代码的测试中31行代码应用了字符串常量池,使用双引号创建字符串与用new完全不同, 29 * 他会检测在栈中的字符串存储池中是否有值为abcedf的字符串, 30 * 如果有则指向它,如果没有,则在栈中创建它。 31 */ 32 System.out.println(s1 == s3);//31 true 33 System.out.println(s1 == s4);//32 false 34 35 System.out.println(s1.equals(s2));// false 36 System.out.println(s1.equals(s3));// true 37 38 /** 39 * 方法三:int length() 40 * 功能:返回字符串的长度 41 */ 42 System.out.println(s1.length()); 43 System.out.println(s2.length()); 44 45 /** 46 * 方法四:String toUpperCase(),将字符串全部转化为大写 47 * String toLowerCase(),将字符串全部转化为小写 48 */ 49 System.out.println(s1.toUpperCase()); 50 System.out.println(s1.toLowerCase()); 51 System.out.println(s2.toUpperCase());//数字也可以大小写,长见识了,但是没卵用 52 System.out.println(s2.toLowerCase()); 53 54 /** 55 * 方法五:boolean equalsIgnoreCase(String str) 56 * 功能:无视大小,比较两字符串是否相同 57 */ 58 System.out.println(s1.equalsIgnoreCase(s5)); 59 60 /** 61 * 方法六:int indexOf(String str , int index) 62 * 功能:返回指定子串的第一次出现的字符串中的索引,从指定的索引开始。 63 */ 64 int index1 = s1.indexOf("abc"); //当然索引处可以不填 65 int index2 = s1.indexOf("e",1); 66 System.out.println(index1); 67 System.out.println(index2); 68 69 /** 70 * 方法七:String substring(int beginIndex,int endIndex) 71 * 功能:截取字符串,左包含,右不包含 72 */ 73 String str6 = s1.substring(1,4); 74 System.out.println(str6); 75 76 /** 77 * 方法八:String replace(char oldchar, char newchar) 78 * 功能:字符(串)替换 79 */ 80 String st7 = s1.replace("a","ppap"); 81 System.out.println(st7); 82 83 /** 84 * 方法九:char[] toCharArray() 85 * 功能:将此字符串转化为字符数组,方便使用数组中的一些API 86 */ 87 System.out.println(s1.toCharArray()); 88 } 89 }