String类
声明字符串
String str=[null]
声明字符串必须结果初始化才能使用,否则编译器会报出“变量未被初始化错误”
String str1,str2;
str1="we are student"
str1="we are student"
此时str1与str2引用相同的字符串变量,因此具有相同的实体
字符串查找
indexOf(substr)
String str="we are student";
int position=str.indexOf("a");
lastIndexOf(substr)
str.lastIndexOf(substr)
获取制定索引位置的字符
str.charAt(int index)
字符串操作
获取子字符串
str.substring(int beginIndex,int endIndex)
去除空格
str.trim()
字符串替换
str.replace(char oldChar,char newChar)
此方法区分大小写
判断字符串的开始和结尾
str.startsWith(String prefix)
str.endsWith(String suffix)
判断当前字符串是否以指定的内容开始或结束
判断字符串是否相等
对字符串对象
进行比较不能简单地使用比较运算符“==”,因为比较运算符比较的是两个字符串的地址是否相同 即使两个字符串的内容相同 两个对象的内存地址也是不同的 使用比较运算符仍然会返回false
String tom=new String("i am a student");
String jerry=new String("i am a student");
boolean b=(tom==jerry);
b=false;
boolean a=tom.equals(jerry);//equalsIgnoreCase()忽略大小写比较
a=false;
字母大小写转换
str.toLowerCase()
str.toUpperCase()
使用以上两个方法进行大小写转换时,数字或非字符不受影响
字符串分割
str.split(String sign)
sign为分割字符串的分割符,也可以使用正则表达式
str.split(String sign,int limit)
限定了分割的次数
字符串生成器
创建成功的字符串对象 其长度是固定的 内容不能被改变和编译 虽然使用+可以达到附加新字符的目的 但是+会产生一个新的String实例 会在内存中创建新的字符串对象 如果重复的对字符串进行修改 将极大的增大系统开销 String-Builder
类大大的提高了频繁增加字符串的效率。
StringBuilder builder=new StringBuilder("");
builder.append();//追加字符串内容
bulider.insert(int offset,int arg);//指定位置插入特定内容 offset位置 arg内容
bulider.delete(int start,int end);//移除从start处开始一直到end-1处的字符