String类特点分析
String类特点分析
1.String类型初始化
- 直接赋值:String var="内容";
- String构造方法赋值:String var=new String("内容");
两种赋值方式的不同在于内容保存地方的不同,直接赋值时JVM基于共享模式设计,会将内容保存在对象池(并不是仅保存String对象)中,当你再次给一个变量(V2)直接赋值相同的内容(注意是通过直接赋值的方法赋值),JVM会在对象池中寻找到这个内容,把他付给V2;构造方法赋值时,JVM会在堆内存中开辟一个新的空间,将内容付给变量。
2、String对象的比较
- == : 比较的是引用变量的地址,即两个对象是否引用同一地址的内容
- equals比较:内容的比较,即两个对象内容上是否相同
3、常用方法总结
字符串与String之间的方法:
- public String([] char):构造方法,将字符数组转为String类型
- public String ([] char ,int offset,int end):构造方法,将自定位置之间的字符转为字符串
- public char charAt(int index):普通方法,返回索引位置的字符
- public char [] toCharArray():普通方法,将String转为字符串数组
字节与String方法:
- public String( byte [] bytes):构造方法,将字节数组转为字符串
- public String (byte [] ,int offset,int end):构造方法,将指定位置的字节转为字符串
- public byte [] getByte( ):普通方法,将字符串转为字节数组
- public byte [] getBytes(Charset charset):普通方法,以指定编码格式返回字符串编码
字符串比较函数
- public boolean equals(String string):普通方法,比较两个字符串的内容,相同返回True
- public boolean equalsIgnoreCase(String string):普通方法,忽略大小写,比较两个字符串内容是否相同
- public int compareTo(String string):普通方法,比较两个字符串的大小,
字符串查找函数
- public boolean contains(String s):普通方法,子字符串s是否在字符串之中,包含,返回True
- public int indexOf(String str):普通方法,索引字符串子字符串str的开始位置
- public int lastIndexOf(String str):普通方法,返回子字符串str在字符串最后开始的位置
- public boolean startWith(String prefix):普通方法,字符串是否以prefix开始
- public boolean endsWith(String prefix):普通方法,字符串会否以指定资字符prefix结尾
字符串替换
- public String replace(String olderStr ,String newStr):普通方法,将oldreStr替换为newStr。
- public StringreplaceAll(String regex,String str):普通方法,将符合正则表达式regex的替换为str
字符串拆分
- public String[] split(String regex):普通方法,将以正则表达式为间隔拆分字符串
- public String[] split(String regex,int limit):普通方法,将以正则表达式为间隔拆分为limit个字符串数组
字符串截取
- public String subString(int beginIndex):普通方法,从beginIndex开始返回子字符串
- public String subString(int begin ,int last):普通方法,返回索引位置在begin,last之间的字符串