String类和StringBuffer类

来源:互联网 发布:新浪博客怎么绑定域名 编辑:程序博客网 时间:2024/06/05 06:51
String类和StringBuffer类
这两个类主要用来处理字符串。这两个类提供了很多字符串的处理方法。String类是不可变类,一个String对象包含的字符串的内容永远不会被改变;而StringBuffer类是可变类,一个StringBuffer类的对象所包含的字符串内容可以被添加或修改。
String类常用方法
length():返回字符串长度
charAT(int index):返回字符串中index位置上的字符
equals(object str):判断两个字符对象的内容是否相同
equalsIgnoreCase(object str):判断两个字符对象的内容是否相同,不区分大小写
compareTo(String str):按字典顺序比较两个字符串的大小
indexOf(String str,int n):在字符串中检索特定的字符或字符串,从第n个位置作为开始,依次向后查找
lastIndexOf(String str,int n):在字符串中检索特定的字符或字符串,从第n个位置作为结尾,依次向前查找
concat():串连接
substring(int begin,int end):求子串,介于begin和end-1之间
split(String regex):用regex分割字符串,存入一个字符串数组中
replaceFirst(String str1,String str2):str2替换第一个str1
replaceAll(String str1,String str2):str2替换全部str1
trim():删除首尾空格
valueOf():把基本类型转换为字符串类型
toUpperCase():把字符串转换成大写
toLowerCase():把字符串转换成小写
PS:
String s1=”hello” String s2=”hello” hello为直接数,虚拟机只会为它分配一次内存,s1.equals(s2)为true
String s1=new String(“hello”) String s2=new String(“hello”)每个new语句都会创建一个新的String对象s1.equals(s2)为false
 
StringBuffer类
表示有缓存的字符串类
StringBuffer类常用方法
append():向缓冲区内添加新的字符串
charAt():与String类的方法相同
setCharAt(int index,char ch):在字符串中的index位置中放置字符ch
insert(int index,String str):在字符串中的index位置插入字符串str
String类与StringBuffer类的区别
String类是不可变类,StringBuffer类是可变类。String对象创建后,一些看起来能够改变字符串的方法,实际上是创建一个带有带有方法所赋予的特性的新的字符串,而StringBuffer类的方法都会改变字符串的内容
String类覆盖了Object类的equals()方法,而StringBuffer类没有覆盖equals()方法
两个类都覆盖了Object类的toString()方法,但实现的方式不一样。在String类中toString()方法返回当前String类实例本身的引用,而StringBuffer类的toString ()方法返回以当前StringBuffer缓冲区中的字符为内容的新String对象的引用
String类对象可以用操作符“+”,SringBuffer类对象之间不能使用“+”
 
原创粉丝点击