一、介绍
·String类表示字符串,用于创建和操作字符串。 Java程序中的所有字符串文字(例如"abc" )都实现为此类的实例。
extends Object
implements Serializable, Comparable, CharSequence
·String类创建的字符串对象存储在常量池中,值在创建后无法更改,所以,当两个字符串对象存储相同的字符串时,其引用为同一块内存,如下:
注:对于基础数据类型,“==”判断为在栈中存储的数据的值,对于引用数据类型(类的实例化对象),判断的是对象引用内存的地址;
·由于字符串存储在字符串常量池中,无法回收,在使用 + 拼接字符串时,会产生大量的无效字符串残留在内存中;所以拼接时,应通过StringBuilder或StringBuffer的append方法进行拼接;
二、构造方法
1.String()
·初始化新创建的 String对象,使其表示空字符序列;
String a1 = new String();
2.String(byte[] bytes)
·通过默认字符集解码指定的字节数组对应的字符数组(ASCII码十进制对应的字符)构造新的字符串
byte[] b = new byte[3];
b[0] = 65;//字符'A'对应十进制ASCII码为65
b[1] = 66;
b[2] = 67;
String s = new String(b);
打印如下
ABC
3.String(byte[] bytes, int offset, int length)
·截取字节数组,并将通过其对应的字符构建字符串
offset表示从数组bytes的offset下标开始
length表示从offset下标开始(包括),截取的字符个数
byte[] b = new byte[3];
b[0] = 65;
b[1] = 66;
b[2] = 67;
String s = new String(b,1,1);
System.out.println(s);
打印如下:
B
注意:若offset或者leng超出数组范围,抛出StringIndexOutOfBoundsException异常;
4.String(byte[] bytes, int offset, int length, String charsetName)
charsetName表示字符解码器的名字,注意导包
mport java.io.UnsupportedEncodingException;
public class Test6 {
public static void main(String[] args) throws UnsupportedEncodingException {
byte[] b = new byte[3];
b[0] = 65;
b[1] = 66;
b[2] = 67;
String s = new String(b,1,1,"ASCII");
System.out.println(s);
}
}
打印如下:
B
5.String(byte[] bytes, int offset, int length, Charset charset)
同4,不同的是,这里的charset是Charset类型的标识符,而非字符串;
import java.nio.charset.StandardCharsets;
public class Test6 {
public static void main(String[] args) {
byte[] b = new byte[3];
b[0] = 65;
b[1] = 66;
b[2] = 67;
String s = new String(b,1,1, StandardCharsets.UTF_8);
System.out.println(s);
}
}
打印如下:
B
6.String(byte[] bytes, String charsetName)
将字节型数组,按照指定名称的解码器解码,用得到的字符数组构建字符串
import java.io.UnsupportedEncodingException;
public class Test6 {
public static void main(String[] args) throws UnsupportedEncodingException {
byte[] b = new byte[3];
b[0] = 65;
b[1] = 66;
b[2] = 67;
String s = new String(b,"ASCII");
System.out.println(s);
}
}
打印如下:
ABC
7.String(byte[] bytes, Charset charset)
将字节型数组,按照指定Charset类型的标识符的解码器解码,用得到的字符数组构建字符串
mport java.nio.charset.StandardCharsets;
public class Test6 {
public static void main(String[] args) {
byte[] b = new byte[3];
b[0] = 65;
b[1] = 66;
b[2] = 67;
String s = new String(b,StandardCharsets.UTF_8);
System.out.println(s);
}
}
打印如下:
ABC
8.String(char[] value)
将字符数组构建至字符串
char [] b = {'a','b','c'};
String s = new String(b);
System.out.println(s);
打印如下:
abc
9.String(char[] value, int offset, int count)
截取字符数组,构建字符串
offset为开始下标,count为截取个数
char [] b = {'a','b','c'};
String s = new String(b,1,1);
System.out.println(s);
打印如下:
b
10.String(int[] codePoints, int offset, int count)
分配新的 String ,其中包含 Unicode code point数组参数的子数组中的字符
int[] b = {65,66,67,68,111222};
String s = new String(b,1,4);
System.out.println(s);
打印如下:
BCD𛉶
11.String(String original)
创建original的字符串副本
注意:String 创建的字符串存储在公共池中,而 new 创建的字符串对象在堆上:
String s = new String("哈哈哈");
String s2 = new String("哈哈哈");
String s3 = "哈哈哈";
String s4 = "哈哈哈";
System.out.println(s==s2);
System.out.println(s==s3);
System.out.println(s3==s4);
结果如下:
false
false
true
JDK1.8后,移除永久代,改为元空间,方法区存储在元空间;
字符串常量池存储在堆中,但运行时,常量池在方法区中;
12.String(StringBuffer buffer)
分配一个字符串对象,包含buffer中的字符串
代码如下:
StringBuffer buffer = new StringBuffer("嘿嘿嘿");
String s = new String(buffer);
System.out.println(s);
打印如下:
嘿嘿嘿
13.String(StringBuilder builder)
同12,创建一个字符串对象,包含builder内的字符串,StringBilder与StringBuffer仅在线程安全方面存在差异;
代码如下:
StringBuilder builder = new StringBuilder("嘿嘿嘿");
String s = new String(builder);
System.out.println(s);
打印如下:
嘿嘿嘿
三、成员方法
1.返回char:charAt(int index)
返回index索引处的字符
代码如下:
String s = "嘿呦羞哈";
System.out.println(s.charAt(2));
打印:
羞
2.IntStream chars()
返回Int流
3.int codePointAt(int index)
返回指定索引处的字符的编码:
String s = "ABC都好看";
System.out.println(s.codePointAt(2));
打印:
67
4.int codePointBefore(int index)
返回索引前字符的编码
String s = "ABC都好看";
System.out.println(s.codePointBefore(2));
打印:
66
5.int codePointCount(int beginIndex, int endIndex)
返回文本范围内代码点数
String s = "ABCS都好看";
System.out.println(s.codePointCount(2,3));
打印:
1
6.IntStream codePoints()
返回代码点值流
7.int compareTo(String anotherString)
从前往后逐个字符比较,首先比较两个字符的ASCII码值,如果不同,结束比较,返回ASCII码的差值;如果字符相等,继续比较,至一方结束:
String s = "ABC";
String s2 = "E";
System.out.println(s.compareTo(s2));
String s = "ABC";
String s2 = "EF";
System.out.println(s.compareTo(s2));
以上两段代码打印结果相同,为A和E的ASCII码差值:
-4
如果都一个字符串的字符全部比较后与另一个对应的字符都相等,则另一个字符串剩余字符个数为两者的差值:
String s = "ABC";
String s2 = "ABC嘿嘿嘿";
System.out.println(s.compareTo(s2));
打印:
-3
8.int compareToIgnoreCase(String str)
比较两个字符串,忽略大小写
String s = "ABC";
String s2 = "abc嘿嘿嘿";
System.out.println(s.compareToIgnoreCase(s2));
打印:
-3
9.String concat(String str)
连接字符串至末尾
String s = "ABC";
String s2 = "abc嘿嘿嘿";
System.out.println(s.concat(s2));
打印
ABCabc嘿嘿嘿
10.boolean contains(CharSequence s)
包含字符序列时,返回true(s为实现CharSequence接口的类)
String s = "ABC";
String s2 = "abc嘿嘿嘿";
System.out.println(s.contains("ABC"));
打印:
true
11.boolean contentEquals(CharSequence cs)
字符串与实现CharSequence的对象比较,如果包含的字符串形同,返回true
String s1 = "abcdefg";
String s2 = "abcdefg";
StringBuffer b3 = new StringBuffer("abcdefg");
StringBuilder b4 = new StringBuilder("abcdefg");
System.out.println(s1.contentEquals(s2));
System.out.println(s1.contentEquals(b3));
System.out.println(s1.contentEquals(b4));
打印如下:
true
true
true
12.boolean contentEquals(StringBuffer sb)
同11,此方法返回调用方法11的结果
public boolean contentEquals(StringBuffer sb) {
return contentEquals((CharSequence)sb);
}
13.static String copyValueOf(char[] data)
返回字符数组按顺序构建的字符串
String s1 = "abcdefg";
char[] b2 = {'c','a','s','e'};
System.out.println(s1.copyValueOf(b2));
打印:
case
14.static String copyValueOf(char[] data, int offset, int count)
offset:开始下标,count:读取字符个数
String s1 = "abcdefg";
char[] b2 = {'c','a','s','e'};
System.out.println(s1.copyValueOf(b2,1,2));
打印:
as
15.boolean endsWith(String suffix)
字符串以suffix表示的字符串结尾时,返回true
String s1 = "abcdefg";
String s2 = "efg";
System.out.println(s1.endsWith(s2));
打印:
true
16.boolean equals(Object anObject)
与对象比较地址是否相等,String重写这个方法用于比较字符串是否相等,当用new创建两个相同字符串内容的字符串对象时,两个对象在堆中的内存地址不同,单用重写的equals方法比较时,返回true
String s1 = new String("aoe");
String s2 = new String("aoe");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
打印:
false
true
注意:当调用此方法的字符串为null时,会NullPointerException空指针报错,而方法内比较的传参字符串为null时,返回false;
17.boolean equalsIgnoreCase(String anotherString)
与另一个String对象比较,忽略大小写
String s1 = new String("HAHA");
String s2 = new String("haha");
System.out.println(s1.equalsIgnoreCase(s2));
打印:
true
18.static String format(String format, Object… args)
使用指定格式字符串和参数返回格式化字符串
静态方法,可直接通过类调用
19.static String format(Locale l, String format, Object… args)
使用指定的语言环境,格式字符串和参数返回格式化的字符串
20.byte[] getBytes()
使用平台的默认字符集将此 String编码为字节序列,将结果存储到新的字节数组中
String s1 = new String("HAHA");
System.out.println(Arrays.toString(s1.getBytes()));
打印:
[72, 65, 72, 65]
21.byte[] getBytes(String charsetName
同方法20,这里指定编码名称
String s1 = new String("HAHA");
System.out.println(Arrays.toString(s1.getBytes("gbk")));
打印:
[72, 65, 72, 65]
22.byte[] getBytes(Charset charset)
同21,这里的编码名称写标识符而不是String
String s1 = new String("HAHA");
System.out.println(Arrays.toString(s1.getBytes(StandardCharsets.UTF_8)));
打印:
[72, 65, 72, 65]
23.getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
复制到目标字符数组,scrBegin:开始下标(包含),intsrcEnd:结束下标(不包含),dest:用于存储数组,desBegin:数组偏移量
String s1 = "abcdefg";
char[] c1 = new char[10];
s1.getChars(1,3,c1,1);
System.out.println(Arrays.toString(c1));
打印:
[ , b, c, , , , , , , ]
24.int hashCode()
返回此字符串的哈希码
String s1 = "abcdefg";
System.out.println(s1.hashCode());
打印:
-1206291356
25.int indexOf(int ch)
返回字符第一次出现的索引,若找不到,返回-1
String s1 = "abcdefg";
System.out.println(s1.indexOf('c'));
System.out.println(s1.indexOf('w'));
打印:
2
-1
26.int indexOf(int ch, int fromIndex)
同方法25,从指定索引处搜索
String s1 = "abcdefg";
System.out.println(s1.indexOf('c',1));
打印:
2
27.int indexOf(String str)
返回指定字符串第一次出现的位置
String s1 = "abcdefg";
System.out.println(s1.indexOf("bc"));
打印:
1
28.int indexOf(String str, int fromIndex)
指定索引开始查找,返回字符串第一次出现的位置
String s1 = "abcdefg";
System.out.println(s1.indexOf("bc",1));
打印:
1
29.String intern()
返回字符串对象的规范表示
String s1 = "abcdefg";
System.out.println(s1.intern());
打印:
abcdefg
30.boolean isBlank()
如果为空。或只包含空格,返回true
String s1 = " ";
System.out.println(s1.isBlank());
打印:
true
31.boolean isEmpty()
长度为零时,返回true,注意:长度为零,而不是null
String s1 = "";
System.out.println(s1.isEmpty());
打印:
true
32.static String join(CharSequence delimiter, CharSequence… elements
返回由 CharSequence elements的副本组成的新String,该副本与指定的 delimiter的副本连接在一起
String s1 = "aaa";
String s2 = "bbb";
String s3 = "ccc";
System.out.println(s1.join(s2,s3));
打印:
ccc
33.join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
同方法32
34.int lastIndexOf(int ch)
返回字符最后出现的位置,ch为字符对应的ASCII码
String s1 = "aaasdgsgfsdfd";
System.out.println(s1.lastIndexOf(97));
打印:
2
35.int lastIndexOf(int ch, int fromIndex)
返回指定字符最后一次出现的字符串中的索引,从指定的索引开始向前搜索
String s1 = "aaasdgsgfsdfd";
System.out.println(s1.lastIndexOf(97,1));
打印:
1
36.int length()
返回字符串长度
String s1 = "aaasdgsgfsdfd";
System.out.println(s1.length());
打印:
13
37.Stream lines()
返回从此字符串中提取的行的流,由行终止符分隔
38.boolean matches(String regex)
String s1 = "acd";
System.out.println(s1.matches("acd"));
打印:
true
39.int offsetByCodePoints(int index, int codePointOffset)
返回此 String中的索引(偏移后),该索引从给定的 index偏移 codePointOffset位索引
String s1 = "acdefg";
System.out.println(s1.offsetByCodePoints(1,3));
打印:
4
40.boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
ignoreCase – 如果为 true,则比较字符时忽略大小写
toffset – 此字符串中子区域的起始偏移量
other – 字符串参数
ooffset – 字符串参数中子区域的起始偏移量
len – 要比较的字符数
String s1 = "acdefg";
System.out.println(s1.regionMatches(true,2,"DEF",0,2));
打印:
true
41.boolean regionMatches(int toffset, String other, int ooffset, int len)
方法40的重载
42.String repeat(int count)
返回一个字符串,其值为此字符串的串联重复 count次
String s1 = "acdefg";
System.out.println(s1.repeat(3));
打印:
acdefgacdefgacdefg
43.String replace(char oldChar, char newChar)
替换oldChar为newChar
String s1 = "acdefg";
System.out.println(s1.replace('c','a'));
打印:
aadefg
44.String replace(CharSequence target, CharSequence replacement)
将target字符串替换为replacment字符串
String s1 = "acdefg";
System.out.println(s1.replace("cd","aa"));
打印:
aaaefg
45.String replaceAll(String regex, String replacement)
替换所有regex为replacement,regex可使用正则
String s1 = "acccfcccg";
System.out.println(s1.replaceAll ("c(.)c","aa"));
打印:
aaafaag
46.String replaceFirst(String regex, String replacement)
替换第一个匹配的字符串
String s1 = "acccfcccg";
System.out.println(s1.replaceFirst ("c(.)c","aa"));
aaafcccg
47.String[] split(String regex)
用regex对字符串进行分割(可正则)
String s1 = "acccfcccg";
System.out.println(Arrays.toString(s1.split("c(.)c")));
打印:
[a, f, g]
48.String[] split(String regex, int limit)
同方法47,这里指定limit,分割的分数
String s1 = "acccfcccg";
System.out.println(Arrays.toString(s1.split("c(.)c",2)));
打印:
[a, fcccg]
49.boolean startsWith(String prefix)
如果以prefix内的字符串开头,返回true
String s1 = "acccfcccg";
System.out.println(s1.startsWith("acc"));
打印:
true
50.boolean startsWith(String prefix, int toffset )
指定索引处以指定字符串开始时,返回true
String s1 = "acccfcccg";
System.out.println(s1.startsWith("ccf",2));
打印:
true
51.String strip()
删除首位空格
String s1 = " acccfcccg ";
System.out.println(s1.strip());
打印:
acccfcccg
52.String stripLeading()
删除前导字符串
53.String stripTrailing()
删除尾随字符串
54.CharSequence subSequence(int beginIndex, int endIndex)
截取字符串,包含beginIndex,不包含endIndex
String s1 = "acccfcccg";
System.out.println(s1.subSequence(1,5));
打印:
cccf
55.String substring(int beginIndex)
返回次字符串的子字符串
public static void main(String[] args) {
String a = "哈哈哈";
System.out.println(a.substring(2));
}
打印:
哈
56.String substring(int beginIndex, int endIndex)
同方法54,其调用这个方法作为返回
public CharSequence subSequence(int beginIndex, int endIndex) {
return this.substring(beginIndex, endIndex);
}
57.char[] toCharArray()
转换为字符数组
public static void main(String[] args) {
String a = "哈哈哈嘿嘿呵呵";
System.out.println(Arrays.toString(a.toCharArray()));
}
打印:
[哈, 哈, 哈, 嘿, 嘿, 呵, 呵]
58.String toLowerCase()
转换为小写
public static void main(String[] args) {
String a = "ASDFKJH";
System.out.println(a.toLowerCase());
}
打印:
asdfkjh
59.String toLowerCase(Locale locale)
按照Local转换为小写
public static void main(String[] args) {
String a = "ASDFKJH";
System.out.println(a.toLowerCase(Locale.JAPAN));
}
打印:
asdfkjh
60.String toString()
重写的toString方法,返回this
public String toString() {
return this;
}
61.String toUpperCase()
转换为大写
public static void main(String[] args) {
String a = "abcde";
System.out.println(a.toUpperCase());
}
打印:
ABCDE
62.String toUpperCase(Locale locale)
转换为大写,指定Local
public static void main(String[] args) {
String a = "abcdφ";
System.out.println(a.toUpperCase(Locale.FRANCE));
}
打印:
ABCDΦ
63.String trim()
删除前导和尾随空格
public static void main(String[] args) {
String a = " abcd ";
System.out.println(a.trim());
}
abcd
64.static String valueOf(boolean b)
static String valueOf(boolean b) 返回 boolean参数的字符串表示形式。
static String valueOf(char c) 返回 char参数的字符串表示形式。
static String valueOf(char[] data) 返回 char数组参数的字符串表示形式。
static String valueOf(char[] data, int offset, int count) 返回 char数组参数的特定子数组的字符串表示形式。
static String valueOf(double d) 返回 double参数的字符串表示形式。
static String valueOf(float f) 返回 float参数的字符串表示形式。
static String valueOf(int i) 返回 int参数的字符串表示形式。
static String valueOf(long l) 返回 long参数的字符串表示形式。
static String valueOf(Object obj) 返回 Object参数的字符串表示形式。
public static void main(String[] args) {
System.out.println(String.valueOf(123));
}
打印:
123
结束
几个返回值为流的方法,学完后再补
如有错误,还望指正