1. 程式人生 > 實用技巧 >String類常用的方法

String類常用的方法

(1)int length():返回字串的長度,例如:

String s1="hello";
System.out.println(s1.length());//顯示為5

(2)char charAt(int index):獲取字串中指定位置的字元,index的取值範圍是0~字串長度-1,例如:

String s1="hello world",
System.out.println(s1.charAt(6));//顯示結果為w

(3)int compareTo(String another):按Unicode碼值逐字元比較兩個字串的大小。如果源串較小就返回一個小於0的值;兩串相等返回0;否則返回大於0的值,例如:

System.out.println("hello".compareTo("Hello"));//顯示-4
System.out.println("hello".compareTo("hello"));//顯示0
System.out.println("Hello".compareTo("hello"));//顯示1

(4)String concat(Striing str):把字串str附加在當前字串末尾,例如:

String str ="hello";
String str2="world";
System.out.println(str);//顯示hello
System.out.println(Str2);//
顯示helloworld

(5)equals(Object obj)和equalsIgnoreCase(String str):判斷兩個字串物件的內容是否相同。兩者區別在於,equals()方法區分字母大小寫,equalsIgnoreCase()不區分,例如:

String str1="hello";
String str2="Hello"
System.out.println(str1.equals(str2));//顯示true
System.out.println(str1.equalsIgnoreCase(str2));//顯示false

(6)int indexOf(int ch):返回指定字元ch在此字串中第一次出現的位置。

int indexOf(String str):返回指定字串str在此字串中第一次出現的位置。

int lastIndexOf(int ch):返回指定字元ch在此字串中最後一次出現的位置。

int lastIndexOf(String str):返回指定子字串str在此字串中最後一次出現的位置。

String str1="hello world";
System.out.pritnln(s1.indexOf("l"));//顯示2
System.out.println(s1.indexOf("world"));//顯示6
System.out.println(s1.lastIndexOf("l"));//顯示9
System.out.println(s1.lastIndexOf("world"));//顯示6

(7)String toUpperCase():將字串轉換為大寫。

String toLowCase():將字串轉換成小寫。例如:

String s1="Welcome to Java world";
System.out.println(s1.toUpperCase());//顯示WELCOME TO JAVA WORLD
System.out.println(s1.toLowerCase());//顯示welcome to java world

(8)String substring(int beginIndex):返回一個新字串,改子字串從指定索引處的字元開始,直到此字串末尾。

String substring(int beginIndex,int endIndex):返回一個新字串,改子字串從指定的beginIndex處開始,直到索引endIndex-1處的字元。例如:

String s1="Welcome to Java world";
System.out.println(s4.substring(11));//顯示Java world
System.out.println(s1.substring(11,15));//顯示Java

(9)static String valueOf():把基本資料型別轉換為String型別,例如:

int i=123;
String s1=String.valueOf(i);
System.out.println(s1);//顯示字串123

(10)String[] split(String regex):將一個字串按照指定的分隔符分隔,返回分隔符後的字串陣列。