一、字符串相关类
1. String类
String类的常用方法
返回值为String字符串:
public String toLowerCase()
将字符串转换为小写
public String toUpperCase()
将字符串转换为大写
public String(byte[]bytes)
使用平台的默认字符集解码,将字节数组转换为字符串
public String(byte[]bytes,Charset charset)
使用指定字符集解码,将字节数组转换为字符串
public String substring(int beginIndex)
从beginIndex索引位置开始,到字符串末尾,截取字符串
public String substring(int beginIndex,int endIndex)
从beginIndex索引位置开始,到endIndex-1,截取字符串
public String trim()
返回一个字符串,这个字符串删除了前导和尾随空格
public String[] split(String regex)
通过指定的正则表达式拆分字符串,将拆分后的结果作为一个字符串数组返回
返回值为char字符:
public char charAt(int index)
根据索引位置获取字符串中的某个字符
public char[] toCharArray()
将字符串转换为字符数组
返回值为byte字节:
public byte[] getBytes()
将字符串转换为字节数组
返回值为int:
public int indexOf(String str)
返回参数字符串在当前字符串中的索引位置
public int lastIndexOf(String str)
从后往前找参数字符串,返回参数字符串在当前字符串中的索引位置
public int length()
返回当前字符串的长度
返回值为boolean:
public boolean contains(CharSequence s)
判断当前对象代表的字符串是否包含参数字符串内容
public boolean equals(Object anObject)
判断字符串内容是否相同
2. StringBuffer类
定义:字符串缓冲区
工作原理:预先申请一块内存,存放字符序列,如果字符序列满了,会重新改变缓存区的大小,以容纳更多的字符序列。
特点:是可变对象,这个是与String最大的不同(如果连续操作String对象,则会产生大量的“垃圾”,而且“断开-连接”很频繁。)
package stringbuffer;
public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
sb.append("hello");
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
sb.append(i);
}
long end = System.currentTimeMillis();
System.out.println("使用StringBuffer耗时:" + (end - start));
System.out.println(sb.length());
// sb.append("abc").append(false).append(12.5);
}
}
package stringbuffer;
public class StringBufferMethod {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
sb.append("中国").append("香水").append("Java");
System.out.println("反转之前:");
System.out.println(sb.toString());
sb.reverse(); // 反转缓冲区的内容
System.out.println("反转之后:");
System.out.println(sb.toString());
StringBuffer sb2 = new StringBuffer();
sb2.append(false).append(12.5).append("hello");
sb2.insert(1, true); // 在索引为1处插入true
System.out.println(sb2);
}
}
3. StringBuilder类
和StringBuffer功能几乎是一样的
只是StringBuilder是线程不安全的
二、内部类
1. 特点
内部类的类名不能与包含它的类名相同(因为在外部使用它时,必须给出类的全名)
内部类可作为其他类的成员,并且可以访问它所在类的成员
2. 声明方式
再类或类的方法中声明,并在类的内部使用(可多次)
用new操作符声明匿名内部类,并立即创建一个对象
三、包装类(基本数据类型)
Integer intValue = new Integer(1);
2. 包装类转换成基本类型
Integer integerId=new Integer(2);
intintId=integerId.intValue();
Copyright © 2017 Jin Hanquan. All rights reserved.