String類
String
- 字符串是常量,創建之後不可改變
- 字符串字面值存儲在字符串池中,可以共享
- String s = “Hello”;產生一個對象,字符串池中存儲
- String s = new String(“Hello”); //產生兩個對象,堆,池各存儲一個
package strings;
public class TestString {
public static void main(String[] args) {
String s3 = new String("123");
String s1 = "123";
String s2 = "123";
System.out.println(s1 == s2);
System.out.println(s1 == s3);
}
}
常用方法
-
public char charAt(int index) :根據下標獲取字符
-
public boolean contains(String str) :判斷當前字符串中是否包含str
-
public char[] toCharArray() : 將當前字符串轉換成數組
-
public int indexOf(String str) :查找str首次出現的下標,存在,則返回該下標,不存在,則返回-1
-
public int lastIndexOf(String str) : 查找字符串在當前字符串中最後一次出現的下標索引
-
public int length() : 返回字符串的長度
-
public String trim() : 去掉字符串前後的空格
-
public String toUpperCase() : 將小寫轉成大寫
-
public boolean endWith(String str) : 判斷字符串是否以str結尾
-
public String replace(char oldChar ,char new Char) : 將舊字符串替換成新字符串
-
public String[] split(String str) :根據str做拆分
可變字符串
-
StringBuffer : 可變長字符串,JDK1.0提供,運行效率慢,線程安全
-
StringBuilder : 可變長字符串,JDK5.0提供,運行效率快,線程不安全
package strings;
public class TestStringBuffer {
public static void main(String[] args) {
String empName = "John";
String email = appendEnds(empName);
System.out.println(email);
}
public static String appendEnds(String email){
StringBuffer buffer = new StringBuffer(email);
buffer.append("@qq.com");
return buffer.toString();
}
}