String:
String是一个特殊的对象,一旦被初始化,就不会被改变。()指的是abc 不是变量 s1.String s1="abc"; s1是一个类类型变量,“abc”是一个对象。String s2=new String("abc");s1和s2的区别:s1在字符串常量池中创建了一个abc字符串s2在堆中创建了两个对象一个是默认对象一个是字符串对象。==和equals的区别==比较的是地址,equals比较的是内容。
String类中常见的方法:
1.获取 1.1 获取字符串长度 int length();
1.2 根据位置获取字符 char charAt(int index);
1.3 根据字符获取在字符中的位置 int indexof(int ch) 返回的是ch在字符串中第一个出现的位置 int indexof(int ch,int FromIndex) 从fromIndex指定位置开始,获取ch在字符串中出现的位置 int indexof(String str); 返回的是str在字符串中第一个出现的位置 int indexof(String str,int FromIndex) 从fromIndex指定位置开始,获取str在字符串中出现的位置 反响索引一个字符出现的位置。 int lastindexof(int ch) 返回的是ch在字符串中第一个出现的位置 int lastindexof(int ch,int FromIndex) 从fromIndex指定位置开始,获取ch在字符串中出现的位置 int lastindexof(String str); 返回的是str在字符串中第一个出现的位置 int lastindexof(String str,int FromIndex) 从fromIndex指定位置开始,获取str在字符串中出现的位置
1.4获取字符串中的一部分字符串,也叫子串。 String subString(int beginindex,intendindex) ; String subString(int beginindex).
2.判断:
2.1两个字符串是否相同 equals(Object obj) equalsIgnoreCase(String str)
2.2字符串中是否包含某个字符串 contains(String str)
2.3两个字符串是否以指定字符串开头或结尾 boolean Startswith(String); boolean endswith(String);
2.4字符串是否为空 boolean isEmpty();
3.字符串转换:
3.1将字符串变成字符串数组 String[] split(String regex);
3.2将字符串变成字符数组 char[] toCharArray();
3.3将字符串变成字节数组 byte[] getBytes();
3.4将字符串数组变成字符串 构造函数 String(char[]) String(char[],offset,count)将字符数组中的一部分转成字符串。 静态函数 static String copyValueof(char[]) static String copyValueof(char[],offset,count)将字符数组中的一部分转成字符串。
3.5将字符串的字母大小写转换 String toUppercase();大写 String toUppercase();小写
3.6将字符串的内容替换 String repalce(char oldch,char newch); String repalce(String s1,String s2);
3.7将字符串两端空格去掉 String trim();
3.8将字符串进行连接 String concat(String);
4.比较:
compareTo();小返回负数 等返回0 大返回正数。
StringBuffer:
是个字符串缓冲区对象,用于存储数据的容器特点:
1.长度是可变的
2.可以存储不同类型数据
3.最终要转换成字符串使用
4.可以对字符串进行修改
功能:
1.添加 append(data)将指定数据添加到已有数据的结尾处 insert(位置,字符串) 将数据插入到指定位置
2.删除 delete(start,end) 删除缓冲区中的数据,包含start不包含end deleteCharAt(ine index)删除指定位置元素 StringBuffer.delete(0,sb.length());
3.查找 char charAt(index); int indexof(string) int lastindexof(String);
4.修改 StringBuffer replace(start,end.String) void setCharAt(index,char) setlength()设置长度
5.反转 StringBuffer reverse();
6.将缓冲区中的指定数据存储到字符数组中 void getChars(int srcBegin,int srcEnd,char[] dst,int dstbegin)
StringBuilder 线程不同步的,StringBuffer是同步的。建议使用StringBuilder效率快。
JAVA 升级 :提高效率 简化书写 提高安全性