Loading

Java总结:字符串详解

更新时间:2018-1-6 21:20:39

更多请查看在线文集:http://android.52fhy.com/java/index.html


String

字符串创建

String str1="ABC";//推荐使用
String str2 = new String("ABC"); 

第一种更省空间。对于字符串比较,如果直接使用==是判断地址是否相同,判断值是否相同需要使用String.equals()方法。

对于字符串:其对象的引用都是存储在栈中的,如果是编译期已经创建好(直接用双引号定义的)的就存储在常量池中,如果是运行期(new出来的)才能确定的就存储在堆中。对于equals相等的字符串,在常量池中永远只有一份,在堆中有多份。

直接赋值可能创建一个对象或者不创建对象:如果"ABC"这个字符串在java String池里不存在,会在java String池创建这个一个String对象("ABC");如果已经存在,str1直接reference to 这个String池里的对象。

new操作至少创建一个对象,也可能两个。因为用到new关键字,会在堆里(heap)创建一个 str2 的String 对象,它的value 是 "ABC"。同时,如果"ABC"这个字符串在java String池里不存在,会在java String池创建这个一个String对象("ABC")。

字符串内容是不可以被更改的。字符串相加更改的是堆内存地址的指向。

字符串的常用方法

  • length() 字符串长度
  • toCharArray() 将字符串变成字符数组
  • CharAt(int i) 字符串在偏移处的字符
  • getBytes(String decode) 使用指定的字符集将字符串编码为 byte 序列,并将结果存储到一个新的 byte 数组中。参数为空则获得一个操作系统默认的编码格式的字节数组
  • indexOf(String str) 返回指定子字符串在此字符串中第一次出现处的索引
  • trim() 返回字符串的副本,忽略前导空白和尾部空白
  • substring(int start, int end) 返回一个新字符串,它是此字符串的一个子字符串
  • toLowerCase() 使用默认语言环境的规则将此 String 中的所有字符都转换为小写
  • toUpperCase() 使用默认语言环境的规则将此 String 中的所有字符都转换为大写
  • startsWith(String prefix) 测试此字符串是否以指定的前缀开始
  • endsWith(String suffix) 测试此字符串是否以指定的后缀结束
  • replace(char oldChar, char newChar) 返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的

StringBuffer

StringBuffer是String缓存区,本身也是操作字符串,但是与String不同,StringBuffer是可以被更改的,每次修改不会像String那样重新开辟空间。

通过StringBuffer处理完字符串后,我们需要使用new String(StringBuffer str)或者StringBuffer.toString()将StringBuffer转换为最终的字符串。

下面的例子演示StringBuffer是可变的:

public class StringDemo01 {

	public static void main(String[] args) {
		StringBuffer s = new StringBuffer("hello");
		append(s);
		System.out.println(s.toString());

	}
	
	public static void append(StringBuffer s) {
		s.append(" world");
	}

}

运行输出:
hello world

如果改成String:

public class StringDemo01 {

	public static void main(String[] args) {
		String s = new String("hello");
		append(s);
		System.out.println(s);

	}
	
	public static void append(String s) {
		s+= " world";
	}
}

运行输出:
hello

StringBuffer的常用方法:

  • append(String str) 拼接字符串,类似于字符串的操作符+号
  • insert(int offset, String str) 在偏移处插入内容
  • replace(int offset, int end, String str) 替换字符串
  • indexOf(String str) 返回指定子字符串在此字符串中第一次出现处的索引

StringBuffer使用场景:
如果在一个循环中对字符串进行修改操作,那么请使用StringBuffer代替String。

StringBuilder

1、一个可变的字符串序列,和StringBuffer类似。该类被设计为StringBuffer的一个简易替换。当用在字符串缓存区被单个线程使用的时候,建议使用该类,速度比StringBuffer快。
2、但是如果涉及到线程安全方面,则建议使用StringBuffer。

由于StringBuilder与StringBuffer类似,这里不再详细举例说明。

posted @ 2018-01-07 23:12  飞鸿影  阅读(416)  评论(0编辑  收藏  举报