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();
}
}