String:不可变字符串
StringBuffer:可变字符串
StringBuilder:可变字符串
创建String对象可以通过构造方法实现,常用的构造方法如下:
- String():使用空字符串创建并初始化一个新的String对象String(String original):使用另外一个字符串创建并初始化一个新的String对象String(StringBuffer buffer):使用可变字符串对象(StringBuffer)创建并初始化一个新的String对象String(StringBuilder builder):使用可变字符串对象(StringBuilder)创建并初始化一个新的String对象String(byte[ ] bytes):使用平台的默认字符集解码指定的byte数组,通过byte数组创建并初始化一个新的String对象String(char[ ] value):通过字符数组创建并初始化一个新的String对象String(char[ ] value,int offset,int count):通过字符数组的子数组创建并初始化一个新的String对象,offset参数是子数组第一个字符的索引,count参数指定子数组的长度。
//演示代码
public class CharacterString {
public static void main(String[] args) {
String s1 = new String();
String s2 = new String("HelloWorld");
String s3 = new String("u0048u0065");
System.out.println("s2=" + s2);
System.out.println("s3=" + s3);
char chars[] = {'a', 'b', 'c', 'd', 'e'};
//通过字符数组创建字符串对象
String s4 = new String(chars);
//通过子字符数组创建字符串对象
String s5 = new String(chars, 1, 4);
System.out.println("s4=" + s4);
System.out.println("s5=" + s5);
byte bytes[] = {97, 98, 99};
//通过byte数组创建字符串对象
String s6 = new String(bytes);
System.out.println("s6=" + s6);
System.out.println("s6字符串长度=" + s6.length());//获取字符串长度使用length()方法
}
}
//输出结果
s2=HelloWorld
s3=He
s4=abcde
s5=bcde
s6=abc
s6字符串长度=3
字符串查找
String类中提供了indexOf和lastIndexOf方法用于查找字符或字符串,返回值是查找的字符或字符串所在的位置,-1表示没找到。这两个方法有多个重载版本。
int indexOf(int ch):从前往后搜索字符ch,返回第一次找到字符ch所在处的索引int indexOf(int ch, int fromIndex):从指定的索引开始从前往后搜索字符ch,返回第一次找到字符ch所在处的索引int indexOf(String str):从前往后搜索字符串str,返回第一次找到字符串str所在处的索引int indexOf(String str,int fromIndex):从指定的索引开始从前往后搜索字符串str,返回第一次找到字符串str所在处的索引int lastIndexOf(int ch):从后往前搜索字符ch,返回第一次找到字符ch所在处的索引int lastIndexOf(int ch,int fromIndex):从指定的索引开始从后往前搜索字符ch,返回第一次找到字符ch所在处的索引int lastIndexOf(String str)):从后往前搜索字符串str,返回第一次找到字符串str所在处的索引int lastIndexOf(String str,int fromIndex):从指定的索引开始从后往前搜索字符串str,返回第一次找到字符串str所在处的索引
字符串本质上是字符数组,因此也有索引,从零开始。
String的charAt(int index)方法可以返回索引index所在位置的字符



