目录
1.char charAt(int index)
2. int length()
3. boolean isEmpty()
4. boolean equals(Object anObject)
5. boolean equalsIgnoreCase(String anotherString)
6. boolean contains(CharSequence s)
7. boolean startsWith(String prefix)
8. boolean endsWith(String suffix)
9. int compareTo(String anotherString)
10. int compareToIgnoreCase(String str)
11. int indexOf(String str)
12. int indexOf(String str, int fromIndex)
运行结果:
13. int lastIndexOf(String str)
14. int lastIndexOf(String str, int fromIndex)
应用场景总结1:
一、编码转换:getBytes() 系列方法
(1) byte[ ] getBytes()
对字符串 "Hello, 世界!" 进行分析
英文字符和标点符号部分
中文字符部分
(2) byte[ ] getBytes(String charsetName)
(3) byte[ ] getBytes(Charset charset)
二、 字符数组转换:char[ ] toCharArray()
三、 大小写转换:toLowerCase() 与 toUpperCase()
四、 String concat(String str) 和 + 运算符
五、子串截取:substring()
(1) substring(int beginIndex)
(2) substring(int beginIndex, int endIndex)
(3) 注意事项
六、去除空白:trim() 与 strip()
(1) String trim()
(2) String strip()(Java 11+)
(3) 其他相关方法
七、String intern() 功能:
八、static String join()(Java 8+)
九、static String valueOf()
1.char charAt(int index)
该方法用于返回指定索引位置的字符,索引从 0 开始。若索引超出字符串长度范围,会抛出 StringIndexOutOfBoundsException
异常。
public class StringMethodDemo {public static void main(String[] args) {String str = "Hello";String str1 = "你好,世界";char ch = str.charAt(1);char ch1 = str1.charAt(3);System.out.println("索引 1 处的字符是: " + ch);System.out.println("索引 3 处的字符是: " + ch1);}
}
运行结果:
2. int length()
此方法用于获取字符串的长度,即字符串中字符的个数。
@Testpublic void testLength() {// 注意:数组是length属性。字符串是length()方法。System.out.println("你好世界".length());}
运行结果:
3. boolean isEmpty()
该方法用于判断字符串是否为空,当字符串长度为 0 时返回 true
,否则返回 false
。
@Testpublic void testIsEmpty() {String s = "";System.out.println(s.isEmpty()); // trues = "hello";System.out.println(s.isEmpty()); // falses = " ";System.out.println(s.isEmpty()); // false}
运行结果:
4. boolean equals(Object anObject)
用于比较当前字符串和指定对象是否相等,当且仅当参数不为 null
且是一个内容相同的 String
对象时返回 true
。
public class StringMethodDemo {public static void main(String[] args) {String str1 = "Hello";String str2 = "Hello";String str3 = "World";System.out.println("str1 和 str2 是否相等: " + str1.equals(str2)); System.out.println("str1 和 str3 是否相等: " + str1.equals(str3)); }
}
运行结果:
5. boolean equalsIgnoreCase(String anotherString)
比较两个字符串是否相等,比较时会忽略大小写。
public class StringMethodDemo {public static void main(String[] args) {String str1 = "Hello";String str2 = "hello";System.out.println("str1 和 str2 忽略大小写是否相等: " + str1.equalsIgnoreCase(str2)); }
}
运行结果:
6. boolean contains(CharSequence s)
判断当前字符串是否包含指定的字符序列。
public class StringTest1 {public static void main(String[] args) {String str = "Hello World";System.out.println("字符串是否包含 'World': " + str.contains("World"));System.out.println("HelloWorld.java".contains(".java")); // trueSystem.out.println("HelloWorld.java".contains(".txt")); // false}
}
运行结果:
7. boolean startsWith(String prefix)
判断当前字符串是否以指定的前缀开头。
public class StringTest1 {public static void main(String[] args) {String str = "Hello World";System.out.println("字符串是否以 'Hello' 开头: " + str.startsWith("Hello"));System.out.println("http://www.baidu.com".startsWith("http://")); // true}
}
运行结果:
8. boolean endsWith(String suffix)
判断当前字符串是否以指定的后缀结尾。
public class StringTest1 {public static void main(String[] args) {String str = "Hello World";System.out.println("字符串是否以 'World' 结尾: " + str.endsWith("World"));System.out.println("http://www.baidu.com".endsWith(".com")); // true}
}
运行结果:
9. int compareTo(String anotherString)
按字典顺序比较两个字符串,若当前字符串小于参数字符串,返回负整数;若相等,返回 0;若大于,返回正整数。
public class StringMethodDemo {public static void main(String[] args) {String str1 = "apple";String str2 = "banana";String str3 = "apple";System.out.println("str1 和 str2 比较结果: " + str1.compareTo(str2)); System.out.println("str1 和 str3 比较结果: " + str1.compareTo(str3)); }
}
运行结果:
10. int compareToIgnoreCase(String str)
按字典顺序比较两个字符串,比较时忽略大小写。
public class StringMethodDemo {public static void main(String[] args) {String str1 = "Apple";String str2 = "apple";System.out.println("str1 和 str2 忽略大小写比较结果: " + str1.compareToIgnoreCase(str2)); }
}
运行结果:
11. int indexOf(String str)
返回指定子字符串在当前字符串中第一次出现的索引,若未找到则返回 -1。
public class StringMethodDemo {public static void main(String[] args) {String str = "Hello World";System.out.println("'o' 第一次出现的索引: " + str.indexOf("o")); }
}
运行结果:
12. int indexOf(String str, int fromIndex)
从指定索引位置开始搜索,返回指定子字符串在当前字符串中第一次出现的索引,若未找到则返回 -1。
public class StringMethodDemo {public static void main(String[] args) {String str = "Hello World";System.out.println("从索引 5 开始搜索 'o' 第一次出现的索引: " + str.indexOf("o", 5)); }
}
运行结果:![](https://i-blog.csdnimg.cn/direct/307c9a9637dc40e7811f58d16bfbc405.png)
13. int lastIndexOf(String str)
返回指定子字符串在当前字符串中最后一次出现的索引,若未找到则返回 -1。
public class StringMethodDemo {public static void main(String[] args) {String str = "Hello World";System.out.println("'o' 最后一次出现的索引: " + str.lastIndexOf("o")); }
}
运行结果:
14. int lastIndexOf(String str, int fromIndex)
从指定索引位置开始向左搜索,返回指定子字符串在当前字符串中最后一次出现的索引,若未找到则返回 -1。
public class StringMethodDemo {public static void main(String[] args) {String str = "Hello World";System.out.println("从索引 5 开始向左搜索 'o' 最后一次出现的索引: " + str.lastIndexOf("o", 5)); }
}
运行结果;
应用场景总结1:
![](https://i-blog.csdnimg.cn/direct/830d302b88304e4db354a05a3e202352.png)
一、编码转换:getBytes() 系列方法
(1) byte[ ] getBytes()
功能:将字符串按 系统默认字符集(如 UTF-8)编码为字节数组。
示例:
public class StringGetBytesExample {public static void main(String[] args) {// 定义一个包含英文字符和中文字符的字符串String str = "Hello, 世界!";// 调用 getBytes() 方法将字符串转换为字节数组// 如果不指定字符集,会使用平台默认的字符集byte[] bytes = str.getBytes();// 使用增强 for 循环遍历字节数组for (byte b : bytes) {// 打印每个字节的值,字节值之间用空格分隔System.out.print(b + " ");}// 换行System.out.println();}
}
运行结果:
对字符串 "Hello, 世界!"
进行分析
英文字符和标点符号部分
H
:ASCII 码值是 72,在 UTF - 8 中用 1 个字节表示,字节值就是 72。e
:ASCII 码值是 101,在 UTF - 8 中用 1 个字节表示,字节值就是 101。l
:ASCII 码值是 108,在 UTF - 8 中用 1 个字节表示,字节值就是 108。o
:ASCII 码值是 111,在 UTF - 8 中用 1 个字节表示,字节值就是 111。,
:ASCII 码值是 44,在 UTF - 8 中用 1 个字节表示,字节值就是 44。- (空格):ASCII 码值是 32,在 UTF - 8 中用 1 个字节表示,字节值就是 32。
!
:ASCII 码值是 33,在 UTF - 8 中用 1 个字节表示,字节值就是 33。
中文字符部分
- “世”:其 Unicode 编码是
U+4E16
,转换为二进制是0100 1110 0001 0110
。按照 UTF - 8 的 3 字节编码规则,将其拆分为:
- 第一个字节:
11100100
,转换为十进制是 - 28(Java 中byte
是有符号的,11100100
作为有符号数解释就是 - 28)。- 第二个字节:
10111000
,转换为十进制是 - 72。- 第三个字节:
10101101
,转换为十进制是 - 83。- “界”:其 Unicode 编码是
U+754C
,转换为二进制是0111 0101 0100 1100
。按照 UTF - 8 的 3 字节编码规则,将其拆分为:
- 第一个字节:
11100110
,转换为十进制是 - 26。- 第二个字节:
10010110
,转换为十进制是 - 106。- 第三个字节:
10001011
,转换为十进制是 - 121。
(2) byte[ ] getBytes(String charsetName)
功能:按指定字符集(如 "GBK")编码为字节数组。
注意:若字符集名称无效,抛出 UnsupportedEncodingException。
import java.io.UnsupportedEncodingException;public class StringGetBytesWithCharsetNameExample {public static void main(String[] args) {String str = "Hello, 世界!";try {byte[] bytes = str.getBytes("UTF-8");for (byte b : bytes) {System.out.print(b + " ");}System.out.println();} catch (UnsupportedEncodingException e) {e.printStackTrace();}}
}
运行结果:
(3) byte[ ] getBytes(Charset charset)
此方法使用指定的 Charset
对象对字符串进行编码,将其转换为字节数组。
import java.nio.charset.Charset;public class StringGetBytesWithCharsetExample {public static void main(String[] args) {String str = "Hello, 世界!";Charset charset = Charset.forName("UTF-8");byte[] bytes = str.getBytes(charset);for (byte b : bytes) {System.out.print(b + " ");}System.out.println();}
}
运行结果:
二、 字符数组转换:char[ ] toCharArray()
该方法把字符串转换为字符数组,方便对每个字符进行单独处理。
public class StringToCharArrayExample {public static void main(String[] args) {String str = "Hello";char[] charArray = str.toCharArray();for (char c : charArray) {System.out.print(c + " ");}System.out.println();}
}
运行结果:
三、 大小写转换:toLowerCase() 与 toUpperCase()
toLowerCase()
方法将字符串中的所有字符转换为小写形式,toUpperCase()
方法则将字符串中的所有字符转换为大写形式。
public class StringCaseConversionExample {public static void main(String[] args) {String str = "Hello, World!";String lowerCaseStr = str.toLowerCase();String upperCaseStr = str.toUpperCase();System.out.println("小写形式: " + lowerCaseStr);System.out.println("大写形式: " + upperCaseStr);}
}
运行结果:
四、 String concat(String str) 和 + 运算符
concat 方法用于将指定的字符串连接到当前字符串的末尾,返回一个新的字符串。
+ 运算符既可以用于数值相加,也可以用于字符串拼接。
/*
1.concat方法完成字符串的拼接操作。2. + 和 concat() 都可以完成字符串的拼接。3. + :既可以求和,又可以进行字符串的拼接。底层拼接时会创建一个StringBuilder对象,最终调用toString()方法获取到拼接之后的字符串。
+ 拼接null时不会出现空指针异常。String s = "";for(int i = 1; i < 100000000; i++){s = s + i;}4. concat()方法:只能拼接String字符串。拼接null时会出现空指针异常。这种方式底层不会创建StringBuilder对象。直接concat()拼接完
之后返回一个新的字符串对象。5. + 使用居多。但是如果进行大量的字符串拼接操作。这两种方式都不推荐。(大量字符串拼接操作建议使用StringBuilder)*/
@Testpublic void testConcat(){/*1.concat方法完成字符串的拼接操作。2. + 和 concat() 都可以完成字符串的拼接。3. + :既可以求和,又可以进行字符串的拼接。底层拼接时会创建一个StringBuilder对象,最终调用toString()方法获取到拼接之后的字符串。+ 拼接null时不会出现空指针异常。String s = "";for(int i = 1; i < 100000000; i++){s = s + i;}4. concat()方法:只能拼接String字符串。拼接null时会出现空指针异常。这种方式底层不会创建StringBuilder对象。直接concat()拼接完之后返回一个新的字符串对象。5. + 使用居多。但是如果进行大量的字符串拼接操作。这两种方式都不推荐。(大量字符串拼接操作建议使用StringBuilder)*/String s1 = "test";String s2 = null;String s3 = s1 + s2;System.out.println(s3); // "testnull"String s4 = "test";String s5 = null;String s6 = s4.concat(s5); // 空指针异常}
运行结果;
示例代码2:
public class StringConcatenationExample {public static void main(String[] args) {String str1 = "Hello";String str2 = " World!";// 使用 concat 方法拼接String result1 = str1.concat(str2);System.out.println("使用 concat 方法拼接: " + result1);// 使用 + 运算符拼接String result2 = str1 + str2;System.out.println("使用 + 运算符拼接: " + result2);// + 拼接 nullString result3 = str1 + null;System.out.println("使用 + 拼接 null: " + result3);// concat 拼接 null 会抛出空指针异常try {String result4 = str1.concat(null);System.out.println("使用 concat 拼接 null: " + result4);} catch (NullPointerException e) {System.out.println("使用 concat 拼接 null 时抛出空指针异常。");}}
}
运行结果:
总结:
(1)
String concat(String str)
功能:将参数字符串拼接到当前字符串末尾。
特点:
参数必须为
String
类型(不能为null
)。直接操作字符数组,不创建
StringBuilder
对象。若参数为
null
,抛出NullPointerException
。(2)
+
操作符
功能:支持字符串与任意类型拼接(自动调用
toString()
)。特点:
底层使用
StringBuilder
:每次+
操作生成新对象。处理
null
:将null
转为字符串"null"
。(3) 性能对比
少量拼接:
+
更简洁。大量拼接:两者均不高效,应使用
StringBuilder
:
五、子串截取:substring()
(1) substring(int beginIndex)
substring(int beginIndex)
方法从指定的起始索引开始截取字符串,直到字符串的末尾。
-
功能:从
beginIndex
开始截取到字符串末尾。
(2) substring(int beginIndex, int endIndex)
substring[int beginIndex, int endIndex)
方法从起始索引开始截取,到结束索引(不包含结束索引处的字符)为止。
-
功能:截取
[beginIndex, endIndex)
区间子串。
public class StringSubstringExample {public static void main(String[] args) {String str = "Hello, World!";String subStr1 = str.substring(7);String subStr2 = str.substring(0, 5);System.out.println("从索引 7 开始截取: " + subStr1);System.out.println("从索引 0 到 5 截取: " + subStr2);}
}
运行结果;
(3) 注意事项
索引越界:若
beginIndex < 0
或endIndex > length()
,抛出StringIndexOutOfBoundsException
。内存优化:Java 7+ 后
substring
不再共享原字符串的字符数组,避免内存泄漏。
六、去除空白:trim() 与 strip()
(1) String trim()
-
功能:去除字符串 前后 的 ASCII 空白符(空格、制表符
\t
、换行\n
等)。
(2) String strip()
(Java 11+)
-
功能:去除字符串 前后 的所有 Unicode 空白符(包括全角空格
\u3000
)。
(3) 其他相关方法
stripLeading():仅去除前导空白。
stripTrailing():仅去除尾部空白。
@Testpublic void testTrim(){// 去除字符串的前后空白// 注意:trim()方法只能去除什么空白?ASCII码的空白以及制表符tab。(无法去除全角空白)// \u3000就是全角空白String s1 = " abc def ";String s2 = s1.trim();String s33 = s1.strip();System.out.println("===>" + s2 + "<====");System.out.println("===>" + s33 + "<====");String s3 = "\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000a b c\u3000\u3000\u3000\u3000\u3000\u3000\u3000";String s4 = s3.strip(); // Java11新增的。System.out.println("===>" + s4 + "<====");String s5 = s3.stripLeading();//去除头部的空白System.out.println("===>" + s5 + "<====");String s6 = s3.stripTrailing();//去除尾部的空白System.out.println("===>" + s6 + "<====");}
运行结果:
七、String intern() 功能:
功能:将字符串对象的引用放入字符串常量池,并返回池中的引用。
若池中已存在相同内容的字符串,直接返回池中的引用。
若池中不存在,将当前字符串加入池中并返回引用。
public class StringInternExample {public static void main(String[] args) {byte[] bytes = {97, 98, 99, 100};String s = new String(bytes);String s2 = s.intern();System.out.println("s2 是否在常量池: " + (s2 == "abcd"));}
}
运行结果;
注意事项:
显式调用 intern() 可能导致常量池膨胀,需谨慎使用。
适合用于频繁重复的字符串,减少内存占用。
八、static String join()(Java 8+)
功能:用指定分隔符连接多个字符串元素。
方法签名:
// 接收可变参数
static String join(CharSequence delimiter, CharSequence... elements)// 接收可迭代集合
static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
示例代码1:
public class StringTest1 {public static void main(String[] args) {// 连接可变参数String joined1 = String.join("-", "a", "b", "c"); // "a-b-c"System.out.println(joined1);// 连接列表List<String> list = Arrays.asList("Java", "Python", "C++");String joined2 = String.join(" | ", list); // "Java | Python | C++"System.out.println(joined2);}}
运行结果:
示例代码2:
public class StringTest1 {public static void main(String[] args) {String[] elements = {"Java", "Python", "C++"};//这是 Java 8 新增的静态方法,用于将多个字符串以指定的分隔符连接起来String result = String.join(", ", elements);System.out.println("连接后的字符串: " + result);List<String> list = new ArrayList<>();list.add("Apple");list.add("Banana");list.add("Cherry");//同样是 Java 8 新增的方法,用于将 Iterable 集合中的字符串以指定分隔符连接。String result1 = String.join(" - ", list);System.out.println("连接后的字符串: " + result1);}}
运行结果:
九、static String valueOf()
功能:将非字符串类型数据转换为字符串形式。
方法签名与示例:
public class StringValueOfExample {public static void main(String[] args) {// 将 boolean 转换为字符串boolean boolValue = true;String boolStr = String.valueOf(boolValue);System.out.println("布尔值转换为字符串: " + boolStr);// 将 char 转换为字符串char charValue = 'A';String charStr = String.valueOf(charValue);System.out.println("字符转换为字符串: " + charStr);// 将 char[] 转换为字符串char[] charArray = {'H', 'e', 'l', 'l', 'o'};String charArrayStr = String.valueOf(charArray);System.out.println("字符数组转换为字符串: " + charArrayStr);// 将 char[] 部分转换为字符串String partialCharArrayStr = String.valueOf(charArray, 1, 3);System.out.println("字符数组部分转换为字符串: " + partialCharArrayStr);// 将 double 转换为字符串double doubleValue = 3.14;String doubleStr = String.valueOf(doubleValue);System.out.println("双精度浮点数转换为字符串: " + doubleStr);// 将 float 转换为字符串float floatValue = 2.71f;String floatStr = String.valueOf(floatValue);System.out.println("单精度浮点数转换为字符串: " + floatStr);// 将 int 转换为字符串int intValue = 123;String intStr = String.valueOf(intValue);System.out.println("整数转换为字符串: " + intStr);// 将 long 转换为字符串long longValue = 456L;String longStr = String.valueOf(longValue);System.out.println("长整数转换为字符串: " + longStr);// 将 Object 转换为字符串Object obj = new Object();String objStr = String.valueOf(obj);System.out.println("对象转换为字符串: " + objStr);}
}
运行结果:
关键特性:
处理 null:String.valueOf(null) 返回 "null"(不会抛异常)。
对比 toString():
Object obj = null;
String s1 = String.valueOf(obj); // "null"
String s2 = obj.toString(); // NullPointerException