JAVA類—String類(一)
阿新 • • 發佈:2019-01-24
String類 1 字串的宣告 java中用字串" "括起來 字串的宣告:String 字串name; 宣告及初始化:String str="hello"; 2 建立字串 用一個字元陣列建立一個物件 char[] s={'h','e','l','l','o'}; String str=new String(a); 等價於String str=new String("hello"); 提取字元陣列中一部分建立一個字串物件 char[] a={'s','t','u','d','e','n','t'}; String str=new String(a,2,4); 等價於String str=new String("uden"); 引用字串常量來建立字串變數 String str1,str2; str1="hello" str2="hello" 此時Str1與Str2引用相同的字串常量因此具有相同的實體。 3 連線字串 public static void main(String[] args) { String s1="hello"; String s2="java"; String s=s1+" "+s2; System.out.println(s); } 4 獲取字串長度 public static void main(String[] args) { String s1="hello"; String s2="java"; int size1=s1.length(); int size2=s2.length(); System.out.println(size1); System.out.println(size2); } 5 字串的查詢 public class test { public static void main(String[] args) { String s1="hello"; String s2="java"; int size01=s1.indexOf("e"); int size02=s2.lastIndexOf("a"); char c=s1.charAt(4); System.out.println(c); System.out.println(size01); System.out.println(size02); } } 6 獲取子字串 (字串中空格佔用一個索引) public class test { public static void main(String[] args) { String s1="hello"; String s2="java"; String str=s1.substring(3); String str2=s2.substring(0,3); String str1=s2.substring(1,3);左閉右開 System.out.println(str2); System.out.println(str); System.out.println(str1); } } 7 去除空格 public class test { public static void main(String[] args) { String s1=" hello java "; System.out.println(s1.length()); System.out.println(s1.trim().length()); } } 8 字串的替換 replace()方法將指定的字元或字串換成新的字元或字串 public class test { public static void main(String[] args) { String str="address"; String newstr=str.replaceAll("a", "A"); System.out.println(newstr); } }