一、概述
-
字符串是常量,创建之后不可改变
-
字符串字面值存储在字符串池中,可以共享
-
给字符串赋值时,并没有修改数据,而是新开辟一块空间
-
String s="hello"; 产生一个对象,字符串池中存储
-
String s = new String("hello");产生两个对象,堆、池各存储一个
二、常用方法
-
public int length();返回字符串的长度
-
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 String trim();去掉字符串前后的空格
-
public String toUpperCase();将小写转成大写(toLowerCase()将大写转成小写)
-
public boolean endWith(String str);判断字符串是否以str结尾(startWith()是否以str开始)
-
public String replace(char oldChar,char newChar);将旧字符串替换成新字符串
-
public String[] split(String str);根据str做拆分([ , ]表示选择,可以既表示空格做分割,也可以表示,做分割;如果有多个空格或者逗号,可以用[ , ]+ 表示)
-
public boolean equals(String str);比较str是否与字符串相同(equalsIgnoreCase忽略大小写比较字符串)
-
public int compareTo(String str);比较两个字符串的大小,如果str大,返回负数;如果str小,返回正数;如果相等,返回0
-
public String subString(int beginIndex,int endIndex);传入开始和结束的角标,获取字符串
三、可变字符串
-
StringBuffer:可变长字符串,JDK1.0提供,运行效率慢、线程安全
-
StringBuilder:可变长字符串,JDK5.0提供,运行效率快、线程不安全
-
和String的区别:
-
比String效率高
-
比String更节省内存
-
-
方法:
-
append(); 追加
-
insert(int beginIndex,String str); 在传入索引处添加str字符串
-
replace(int beginIndex,int beginIndex,String str); 在传入开始和结束索引处用str替换字符串(含头不含尾)
-
delete(int beginIndex,int beginIndex);删除指定位置的内容(含头不含尾)
-
resever();反转
-