java.lang.String类
表明字符串java
Java 程序中的全部字符串字面值(如 "abc"
)都做为此类的实例实现。正则表达式
特色编程
构造方法 | 说明 |
---|---|
String() * | 初始化一个新建立的 String 对象,使其表示一个空字符序列。 |
String(byte[] bytes) * | 经过使用平台的默认字符集解码指定的 byte 数组,构造一个新的 String。 |
String(char[] value) * | 分配一个新的 String,使其表示字符数组参数中当前包含的字符序列。 |
String(String original) | 初始化一个新建立的 String 对象,使其表示一个与参数相同的字符序列;换句话说,新建立的字符串是该参数字符串的副本。 |
String(byte[] bytes, int offset, int length) | 经过使用平台的默认字符集解码指定的 byte 子数组,构造一个新的 String。 |
String(byte[] bytes, Charset charset) | 经过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String。 |
String(byte[] bytes, int offset, int length, Charset charset) | 经过使用指定的 charset 解码指定的 byte 子数组,构造一个新的 String。 |
String(byte[] bytes, int offset, int length, String charsetName) | 经过使用指定的字符集解码指定的 byte 子数组,构造一个新的 String。 |
String(byte[] bytes, String charsetName) | 经过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String。 |
String(char[] value, int offset, int count) | 分配一个新的 String,它包含取自字符数组参数一个子数组的字符。 |
String(int[] codePoints, int offset, int count) | 分配一个新的 String,它包含 Unicode 代码点数组参数一个子数组的字符。 |
String(StringBuffer buffer) * | 分配一个新的字符串,它包含字符串缓冲区参数中当前包含的字符序列。 |
String(StringBuilder builder) * | 分配一个新的字符串,它包含字符串生成器参数中当前包含的字符序列。 |
package com; public class StringTest { public static void main(String[] args) { // 常见建立字符串的3+1的方式 String str1 = new String(); System.out.println("第一种无参构造方法建立字符串:"+str1); char[] array = {'A','B','C'}; String str2 = new String(array); System.out.println("第二种传入字符数组建立字符串:"+str2); byte[] array2 = {65,66,67}; String str3 = new String(array2); System.out.println("第三种传入字节数组建立字符串:"+str3); String str = "hello"; System.out.println("直接建立字符串:"+str); } }
注意数组
程序当中直接写上双引号的字符串,存在字符串常量池中app
package com; public class StringPool { public static void main(String[] args) { String str1 = "123"; String str2 = "123"; char[] charArray = {'1', '2', '3'}; String str3 = new String(charArray); System.out.println(str1 == str2); System.out.println(str1 == str3); System.out.println(str2 == str3); } }
结果测试
true false false
示意图ui
注意编码
方法摘要 | 描述 |
---|---|
int length() | 返回此字符串的长度。 |
boolean equals(Object anObject) | 将此字符串与指定的对象比较。 (只有参数是同类型且内容相同才返回true) |
boolean equalsIgnoreCase(String anotherString) | 将此 String 与另外一个 String 比较,不考虑大小写。 |
char charAt(int index) | 返回指定索引处的 char 值。 |
String concat(String str) | 将指定字符串链接到此字符串的结尾。 |
int indexOf(String str) | 返回指定子字符串在此字符串中第一次出现处的索引。 |
String substring(int beginIndex) | 返回一个新的字符串,它是此字符串的一个子字符串。 |
String substring(int beginIndex, int endIndex) | 返回一个新字符串,它是此字符串的一个子字符串。(左闭右开) |
char[] toCharArray() | 将此字符串转换为一个新的字符数组。 |
byte[] getBytes() | 使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。 |
byte[] getBytes(Charset charset) | 使用给定的 charset 将此 String 编码到 byte 序列,并将结果存储到新的 byte 数组。 |
byte[] getBytes(String charsetName) | 使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。 |
String replace(char oldChar, char newChar) | 返回一个新的字符串,它是经过用 newChar 替换此字符串中出现的全部 oldChar 获得的。 |
String replace(CharSequence target, CharSequence replacement) | 使用指定的字面值替换序列替换此字符串全部匹配字面值目标序列的子字符串。 |
String replaceFirst(String regex, String replacement) | 使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。 |
String replaceAll(String regex, String replacement) | 使用给定的 replacement 替换此字符串全部匹配给定的正则表达式的子字符串。 |
String trim() | 返回字符串的副本,忽略前导空白和尾部空白。 |
String[] split(String regex) | 根据给定正则表达式的匹配拆分此字符串。 |
String[] split(String regex, int limit) | 根据匹配给定的正则表达式来拆分此字符串。 |
boolean endsWith(String suffix) | 测试此字符串是否以指定的后缀结束。 |
boolean startsWith(String prefix) | 测试此字符串是否以指定的前缀开始。 |
boolean startsWith(String prefix, int toffset) | 测试此字符串从指定索引开始的子字符串是否以指定前缀开始。 |
int compareTo(String anotherString) | 按字典顺序比较两个字符串。 |
int compareToIgnoreCase(String str) | 按字典顺序比较两个字符串,不考虑大小写。 |
boolean contains(CharSequence s) | 当且仅当此字符串包含指定的 char 值序列时,返回 true。 |
查找方法 | 描述 |
---|---|
int indexOf(int ch) | 返回指定字符在此字符串中第一次出现处的索引。 |
int indexOf(int ch, int fromIndex) | 返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。 |
int indexOf(String str) | 返回指定子字符串在此字符串中第一次出现处的索引。 |
int indexOf(String str, int fromIndex) | 返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。 |
int lastIndexOf(int ch) | 返回指定字符在此字符串中最后一次出现处的索引。 |
int lastIndexOf(int ch, int fromIndex) | 返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索。 |
int lastIndexOf(String str) | 返回指定子字符串在此字符串中最右边出现处的索引。 |
int lastIndexOf(String str, int fromIndex) | 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。 |
indexOf 和 lastIndexOf的多种重载方法指针
转换方法 | 描述 |
---|---|
String toLowerCase() | 使用默认语言环境的规则将此 String 中的全部字符都转换为小写。 |
String toLowerCase(Locale locale) | 使用给定 Locale 的规则将此 String 中的全部字符都转换为小写。 |
String toUpperCase() | 使用默认语言环境的规则将此 String 中的全部字符都转换为大写。 |
String toUpperCase(Locale locale) | 使用给定 Locale 的规则将此 String 中的全部字符都转换为大写。 |
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 参数的字符串表示形式。 |
char[] toCharArray() | 将此字符串转换为一个新的字符数组。 |
byte[] getBytes() | 使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。 |
其余方法 | 描述 |
---|---|
String intern() | 返回字符串对象的规范化表示形式。 |
boolean isEmpty() | 当且仅当 length() 为 0 时返回 true。 |
int codePointAt(int index) | 返回指定索引处的字符(Unicode 代码点)。 |
int codePointBefore(int index) | 返回指定索引以前的字符(Unicode 代码点)。 |
int codePointCount(int beginIndex, int endIndex) | 返回此 String 的指定文本范围中的 Unicode 代码点数。 |
boolean contentEquals(CharSequence cs) | 将此字符串与指定的 CharSequence 比较。 |
boolean contentEquals(StringBuffer sb) | 将此字符串与指定的 StringBuffer 比较。 |
static String copyValueOf(char[] data) | 返回指定数组中表示该字符序列的 String。 |
static String copyValueOf(char[] data, int offset, int count) | 返回指定数组中表示该字符序列的 String。 |
static String format(Locale l, String format, Object... args) | 使用指定的语言环境、格式字符串和参数返回一个格式化字符串。 |
static String format(String format, Object... args) | 使用指定的格式字符串和参数返回一个格式化字符串。 |
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) | 将字符今后字符串复制到目标字符数组。 |
int hashCode() | 返回此字符串的哈希码。 |
boolean matches(String regex) | 告知此字符串是否匹配给定的正则表达式。 |
int offsetByCodePoints(int index, int codePointOffset) | 返回此 String 中从给定的 index 处偏移 codePointOffset 个代码点的索引。 |
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) | 测试两个字符串区域是否相等。 |
boolean regionMatches(int toffset, String other, int ooffset, int len) | 测试两个字符串区域是否相等。 |
CharSequence subSequence(int beginIndex, int endIndex) | 返回一个新的字符序列,它是此序列的一个子序列。 |
package com; /** * equals方法的使用 * equalsIgnoreCase 忽略大小写的比较 */ public class StringEquals { public static void main(String[] args) { String str1 = "Hello"; String str2 = "Hello"; char[] array = {'H', 'e', 'l', 'l', 'o'}; String str3 = new String(array); System.out.println(str1.equals(str3)); System.out.println(str2.equals(str3)); System.out.println(str3.equals("Hello")); System.out.println("Hello".equals(str3)); // 推荐常量字符串写在前面。变量写前面可能会出现空指针异常 System.out.println("============="); String str4 = "hello"; System.out.println(str3.equals(str4)); // 忽略大小写 System.out.println(str3.equalsIgnoreCase(str4)); } }
注意事项code
a.equals(b)
和 b.equals(a)
效果同样package com; /** * length() 返回长度 * concat 拼接 * charAt 获取指定索引位置的单个字符 * indexOf 查找首次出现的索引位置,无返回-1 */ public class StringGet { public static void main(String[] args) { System.out.println("Hello world".length()); // 拼接字符串 (String不可变!!) String str1 = "Hello"; String str2 = "World"; String str3 = str1.concat(str2); System.out.println(str1); // 原封不动 System.out.println(str2); // 原封不动 System.out.println(str3); // 新的字符串 // 获取指定索引位置的单个字符 System.out.println("Hello在0号索引位置的字符是:"+"Hello".charAt(0)); System.out.println("Hello在4号索引位置的字符是:"+"Hello".charAt(4)); // 查询参数字符串在原字符串当中出现的第一次索引位置 System.out.println(); String strA = "Hello World Hello1"; System.out.println(strA.indexOf("hello")); // 查不到返回 -1 System.out.println(strA.indexOf("Hello1"));// 首次出现的索引 } }
package com; /** * 字符的截取方法 * substring(int index) * substring(int begin, int end) 【b,n)左闭右开 * */ public class StringSub { public static void main(String[] args) { String str1 = "HelloWorld"; String str2 = str1.substring(5); // 字符串不能发生改变,每当对原值操做就是生产新的字符串 System.out.println(str1); System.out.println(str2); String str3 = str1.substring(4, 7); // 左闭右开 System.out.println(str3); } }
package com; /** * 转换相关的方法 * toCharArray[] 将当前字符串拆分为字符数组 * getBytes() 得到当前字符串的底层字节数组 * replace替换 * valueOf 转换成字符串 * */ public class StringConvert { public static void main(String[] args) { char[] chars = "Hello".toCharArray(); System.out.println(chars[0]); System.out.println(chars.length); System.out.println("==========="); // IO常常用的字节流写入 byte[] bytes = "abc".getBytes(); for (byte b : bytes) { System.out.print(b + "\t"); } System.out.println(); String str1 = "Hi boy"; String str2 = str1.replace("boy", "girl"); System.out.println(str1); System.out.println(str2); System.out.println("==========="); // 八大基本数据类型转换为字符串 int num = 123; double d = 999.999; boolean b = false; char ch = 'a'; System.out.println(String.valueOf(num)); System.out.println(String.valueOf(d)); System.out.println(String.valueOf(b)); System.out.println(String.valueOf(ch)); } }
package com; /** * 分割方法split * String[] split(String regex) * split 的参数 regex是一个正则表达式 * 英文句点“.” 写成“\\.” */ public class StringSplit { public static void main(String[] args) { String str1 = "1,2,3,4,5"; System.out.println(str1); String[] array1 = str1.split(","); for (int i = 0; i < array1.length; i++) { System.out.print(array1[i] + "\t"); } System.out.println(); // 特殊!!使用英文句号时(.) 须要加两个反斜杠 String str2 = "x.y.z"; //String[] array2 = str2.split("."); // 直接用英文点不行 String[] array2 = str2.split("\\."); System.out.println("长度为:" + array2.length); for (String s : array2) { System.out.print(s + "\t"); } } }
package com.practise; /** * 定义一个方法,吧数组{1,2,3}按指定格式拼接成一个字符串。 * 格式参照以下;[word1#word2$word3] */ public class StringPractise { public static void main(String[] args) { int[] nums = {1, 2, 3}; System.out.println(fromArrayToString(nums)); } public static String fromArrayToString(int[] array) { String result = "["; for (int i = 0; i < array.length; i++) { if (i != array.length - 1) { result += "word" + array[i] + "#"; } else { result += "word" + array[i]; } } result += "]"; return result; } }
键盘输入一个字符串,而且统计其中各类字符出现的次数。
package com.practise; import java.util.Scanner; /** * 键盘输入一个字符串,而且统计其中各类字符出现的次数。 * 种类有:大写字母、小写字母、数字、其余 */ public class StringPractise2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("请输入一个字符串:"); String str = sc.nextLine(); char[] chars = str.toCharArray(); int[] count = {0, 0, 0, 0,}; for (char c : chars) { if (c >= 'A' && c <= 'Z') { count[0]++; } else if (c >= 'a' && c <= 'z') { count[1]++; } else if (c >= '0' && c <= '9') { count[2]++; } else { count[3]++; } } System.out.print("大写字母、小写字母、数字、其余依次出现次数:"); for (int i : count) { System.out.print(i + "\t"); } } }
因为String类的对象内容不可改变,因此每当进行字符串拼接时,老是会在内存中建立一个新的对象。例如:
public class StringDemo { public static void main(String[] args) { String s = "Hello"; s += "World"; System.out.println(s); } }
在API中对String类有这样的描述:字符串是常量,它们的值在建立后不能被更改。
根据这句话分析咱们的代码,其实总共产生了三个字符串,即"Hello"
、"World"
和"HelloWorld"
。
引用变量s首先指向Hello
对象,最终指向拼接出来的新字符串对象,即HelloWord
。
由此可知,若是对字符串进行拼接操做,每次拼接,都会构建一个新的String对象,既耗时,又浪费空间。
为了解决这一问题,可使用java.lang.StringBuilder
类。
查阅java.lang.StringBuilder
的API,StringBuilder又称为可变字符序列,它是一个相似于 String 的字符串缓冲区,
经过某些方法调用能够改变该序列的长度和内容。
原来StringBuilder是个字符串的缓冲区,即它是一个容器,容器中能够装不少字符串。而且可以对其中的字符串进行各类操做。
它的内部拥有一个数组用来存放字符串内容,进行字符串拼接时,直接在数组中加入新内容。
StringBuilder会自动维护数组的扩容。原理以下图所示:(默认16字符空间,超过自动扩充)
根据StringBuilder的API文档,经常使用构造方法有2个:
public StringBuilder()
:构造一个空的StringBuilder容器。public StringBuilder(String str)
:构造一个StringBuilder容器,并将字符串添加进去。方法 | 描述 |
---|---|
StringBuilder() | 构造一个不带任何字符的字符串生成器,其初始容量为 16 个字符。 |
StringBuilder(int capacity) | 构造一个不带任何字符的字符串生成器,其初始容量由 capacity 参数指定。 |
StringBuilder(CharSequence seq) | 构造一个字符串生成器,它包含与指定的 CharSequence 相同的字符。 |
StringBuilder(String str) | 构造一个字符串生成器,并初始化为指定的字符串内容。 |
package com; /** * 字符串缓冲区,能够提升字符串的效率 */ public class StringBuilderTest { public static void main(String[] args) { // 无参构造 StringBuilder sb = new StringBuilder(); System.out.println(sb); System.out.println(sb.length()); // 构造一个字符串生成器,并初始化为指定的字符串内容。 StringBuilder sb2 = new StringBuilder("Hello"); System.out.println(sb2); } }
StringBuilder经常使用的方法有2个:
public StringBuilder append(...)
:添加任意类型数据的字符串形式,并返回当前对象自身。public String toString()
:将当前StringBuilder对象转换为String对象。append方法具备多种重载形式,能够接收任意类型的参数。任何数据做为参数都会将对应的字符串内容添加到StringBuilder中。例如:
package com; /** * 经常使用方法 * append 添加任意类型数据的字符串形式,并返回当前对象自身 * 可链式添加!sb.append("hello").append("world"); */ public class StringBuilderTest { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); System.out.println("调用append方法前,sb的值:" + sb); sb.append("world"); System.out.println("调用append方法后,sb的值:" + sb); StringBuilder builder = new StringBuilder(); // 能够添加 任何类型 builder.append("hello "); builder.append("world "); builder.append(true); builder.append(100); // 链式编程 builder.append("\n---------\n").append("world ").append(true).append(100); System.out.println("builder:"+builder); } }
备注:StringBuilder已经覆盖重写了Object当中的toString方法。
经过toString方法,StringBuilder对象将会转换为不可变的String对象。如:
package com; /** * StringBuilder 和 String 之间的转换 * String -> StringBuilder : new StringBuilder("字符串") * StringBuilder -> String : toString() */ public class StringBuilderTest2 { public static void main(String[] args) { String str = "hello"; System.out.println(str); StringBuilder sb = new StringBuilder(str); sb.append(" world"); System.out.println(sb); String s = sb.toString(); System.out.println(s); } }
方法 | 描述 |
---|---|
int capacity() | 返回当前容量。 |
char charAt(int index) | 返回此序列中指定索引处的 char 值。 |
StringBuilder reverse() | 将此字符序列用其反转形式取代。 |
StringBuilder deleteCharAt(int index) | 移除此序列指定位置上的 char。 |
StringBuilder delete(int start, int end) | 移除此序列的子字符串中的字符。 |
StringBuilder append(int i) | 将 int 参数的字符串表示形式追加到此序列。 |
StringBuilder append(boolean b) | 将 boolean 参数的字符串表示形式追加到序列。 |
StringBuilder append(char c) | 将 char 参数的字符串表示形式追加到此序列。 |
StringBuilder append(char[] str) | 将 char 数组参数的字符串表示形式追加到此序列。 |
StringBuilder append(char[] str, int offset, int len) | 将 char 数组参数的子数组的字符串表示形式追加到此序列。 |
StringBuilder append(CharSequence s) | 向此 Appendable 追加到指定的字符序列。 |
StringBuilder append(CharSequence s, int start, int end) | 将指定 CharSequence 的子序列追加到此序列。 |
StringBuilder append(double d) | 将 double 参数的字符串表示形式追加到此序列。 |
StringBuilder append(float f) | 将 float 参数的字符串表示形式追加到此序列。 |
StringBuilder append(long lng) | 将 long 参数的字符串表示形式追加到此序列。 |
StringBuilder append(Object obj) | 追加 Object 参数的字符串表示形式。 |
StringBuilder append(String str) | 将指定的字符串追加到此字符序列。 |
StringBuilder append(StringBuffer sb) | 将指定的 StringBuffer 追加到此序列。 |
StringBuilder appendCodePoint(int codePoint) | 将 codePoint 参数的字符串表示形式追加到此序列。 |
int codePointAt(int index) | 返回指定索引处的字符(统一代码点)。 |
int codePointBefore(int index) | 返回指定索引前的字符(统一代码点)。 |
int codePointCount(int beginIndex, int endIndex) | 返回此序列指定文本范围内的统一代码点。 |
void ensureCapacity(int minimumCapacity) | 确保容量至少等于指定的最小值。 |
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) | 将字符今后序列复制到目标字符数组 dst。 |
int indexOf(String str) | 返回第一次出现的指定子字符串在该字符串中的索引。 |
int indexOf(String str, int fromIndex) | 从指定的索引处开始,返回第一次出现的指定子字符串在该字符串中的索引。 |
StringBuilder insert(int offset, boolean b) | 将 boolean 参数的字符串表示形式插入此序列中。 |
StringBuilder insert(int offset, char c) | 将 char 参数的字符串表示形式插入此序列中。 |
StringBuilder insert(int offset, char[] str) | 将 char 数组参数的字符串表示形式插入此序列中。 |
StringBuilder insert(int index, char[] str, int offset, int len) | 将数组参数 str 子数组的字符串表示形式插入此序列中。 |
StringBuilder insert(int dstOffset, CharSequence s) | 将指定 CharSequence 插入此序列中。 |
StringBuilder insert(int dstOffset, CharSequence s, int start, int end) | 将指定 CharSequence 的子序列插入此序列中。 |
StringBuilder insert(int offset, double d) | 将 double 参数的字符串表示形式插入此序列中。 |
StringBuilder insert(int offset, float f) | 将 float 参数的字符串表示形式插入此序列中。 |
StringBuilder insert(int offset, int i) | 将 int 参数的字符串表示形式插入此序列中。 |
StringBuilder insert(int offset, long l) | 将 long 参数的字符串表示形式插入此序列中。 |
StringBuilder insert(int offset, Object obj) | 将 Object 参数的字符串表示形式插入此字符序列中。 |
StringBuilder insert(int offset, String str) | 将字符串插入此字符序列中。 |
int lastIndexOf(String str) | 返回最右边出现的指定子字符串在此字符串中的索引。 |
int lastIndexOf(String str, int fromIndex) | 返回最后一次出现的指定子字符串在此字符串中的索引。 |
int length() | 返回长度(字符数)。 |
int offsetByCodePoints(int index, int codePointOffset) | 返回此序列中的一个索引,该索引是从给定 index 偏移 codePointOffset 个代码点后获得的。 |
StringBuilder replace(int start, int end, String str) | 使用给定 String 中的字符替换此序列的子字符串中的字符。 |
void setCharAt(int index, char ch) | 将给定索引处的字符设置为 ch。 |
void setLength(int newLength) | 设置字符序列的长度。 |
CharSequence subSequence(int start, int end) | 返回一个新字符序列,该字符序列是此序列的子序列。 |
String substring(int start) | 返回一个新的 String,它包含此字符序列当前所包含字符的子序列。 |
String substring(int start, int end) | 返回一个新的 String,它包含此序列当前所包含字符的子序列。 |
String toString() | 返回此序列中数据的字符串表示形式。 |
void trimToSize() | 尝试减小用于字符序列的存储空间。 |