从概念上讲,Java字符串就是Unicode字符序列。Java中没有内置的字符串类型,而是在标准Java类库中提供了一个预定义类String,每个用双引号引起来的都是字符串都是String类的一个实例。
注意:在Java中字符只以一种形式存在,那就是Unicode(不选择任何特定的编码,直接使用它们在字符集中的编号)。注意与操作系统中的文件系统的编码区分。
创建字符串
在Java语言中将字符串作为对象来处理,可以像创建其他类对象一样来创建字符串对象。例如:
String str1 = new String(“Hello World”);
//或者引用字符串常量
String str2 = “Hello World”;
//或者利用一个字符数组来创建来创建一个字符串对象:
char[] a = {‘H’,’e’,’l’,’l’,’0’};
String str3 = new String(a);
注意:String类是final修饰的,底层实际上是采用了一个final关键字修饰的字符数组来保存字符串,所以String类是不可变类,不可变类总是线程安全的。
连接字符串
在Java中允许使用“+”运算符将多个字符串进行拼接,String类是不可变类,对字符串进行拼接会产生一个新的字符串对象。
例如:
public class Test {
public static void main(String[] args) {
String str1 = "hello";
String str2 = "world";
System.out.println(str1 + " " + System.identityHashCode(str1));
System.out.println(str2 + " " + System.identityHashCode(str2));
//将str1指向拼接后的字符串对象
str1 = str1 + " " + str2;
System.out.println(str1 + " " + System.identityHashCode(str1));
}
}
运行结果:
我们利用System提供的identityHashCode()静态方法用于获取某个对象唯一的HashCode值来判断两个对象是否相同,从运行结果可以看到拼接后的字符串对象不是原来的字符串对象,是新生成的字符串对象。
我们也可以将字符串和其他数据类型进行连接,并且生成一个新的字符串对象。
例如:
public class Test {
public static void main(String[] args) {
String str1 = "hello";
String str2 = str1 + 123;
System.out.println(str2);
}
}
运行结果:
获取字符串信息
获取字符串长度:
使用String类的length()方法可以获取声明的字符串对象的长度。例如:
String str1 = “hello world”;
System.out.println(str1.length());
注意:字符串长度包含空格。
字符串查找:
String类提供了两种查找字符串的方法,即indexOf()和lastIndexOf()方法。这两种方法都允许在字符串中搜索指定条件的字符或字符串。indexOf()方法返回的是搜索的字符或者字符串首次出现的位置,lastIndexOf()方法返回的是搜索的字符或者是字符串最后一次出现的位置,如果没有查到,都返回-1。
例如:
public class Test {
public static void main(String[] args) {
String str1 = "abc abcd abcde abcdf";
System.out.println("字符b第一次出现的位置:" + str1.indexOf('b'));
System.out.println("字符串abcd第一次出现的位置:" + str1.indexOf("abcd"));
System.out.println("字符b最后一次出现的位置:" + str1.lastIndexOf('b'));
System.out.println("字符串abcd最后一次出现的位置:" + str1.lastIndexOf("abcd"));
}
}
运行结果:
获取指定索引位置的字符:
使用charAt()方法可以将指定索引处的字符返回。例如:
public class Test {
public static void main(String[] args) {
String str1 = "abc abcd abcde abcdf";
System.out.println("索引位置为6的字符是:" + str1.charAt(0));
System.out.println("索引位置为6的字符是:" + str1.charAt(6));
System.out.println("索引位置为6的字符是:" + str1.charAt(9));
}
}
运行结果:
字符串其他操作常用API:
获取子串:
str.substring(beginIndex);//返回从指定的索引位置开始截取直到该字符串结尾的子串
str.substring(beginIndex, endIndex);//返回从字符串某一索引位置开始截取至某一索引位置结束的子串
去除空格:
str.trim();//去除字符串内容中的前导空格和尾部空格,返回新的字符串对象
字符串替换:
str.replace(oldChar, newChar);//将指定的字符或字符串替换成新的字符或字符串
判断字符串的开始和结尾:
str.startsWith(String prefix);//判断当前字符串对象是否为以给定的字符串开始
str.endsWith(String suffix);//判断当前字符串对象是否为以给定的字符串结束
按字典顺序比较字符串:
str.compareTo(anotherString);//基于字符串中各字符的Unicode值,按字典顺序比较字符串
str.compareToIgnoreCase(str);//忽略大小写进行按字典顺序比较
字母大小写转换:
str.toLowerCase();//将字符串中所有字母改写为小写字母
str.toUpperCase();//将字符串中所有字母改写为大写字母
字符串分割:
str.split(regex);//将字符串进行分割,并将分割的结果保存在字符串数组中,regex为分隔符
str.split(regex, limit);//将字符串进行分割并限定分割次数