1 创建字符串
1.1 直接赋值
String str1 = "Hello, World!";
1.2 使用构造函数
String str2 = new String("Hello, World!");
1.3 字符数组转字符串
char[] chars = {'H', 'e', 'l', 'l', 'o'};
String str3 = new String(chars);
2 字符串的常用操作
2.1 获取字符串长度
int length = str1.length();
2.2 获取字符串中的字符
char ch = str1.charAt(0); // 获取字符串的第一个字符
2.3 字符串比较
boolean isEqual = str1.equals("Hello, World!");
boolean isIgnoreCaseEqual = str1.equalsIgnoreCase("hello, world!");
//equals(Object anObject) 方法比较两个字符串的内容是否相等。
//equalsIgnoreCase(String anotherString) 方法忽略大小写比较字符串。
2.4 字符串查找
int index = str1.indexOf("World"); // 查找子字符串首次出现的位置
int lastIndex = str1.lastIndexOf("o"); // 查找子字符串最后一次出现的位置
2.5 提取子字符串
String subStr = str1.substring(7); // 从索引7开始提取子字符串
String subStr2 = str1.substring(7, 12); // 提取索引7到12之间的子字符串
3 字符串的拼接与连接
3.1 使用 +
操作符
String greeting = "Hello, " + "World!";
3.2 使用 concat()
方法
String str4 = "Hello".concat(", World!");
3.3 使用 StringBuilder
或 StringBuffer
StringBuilder sb = new StringBuilder();
sb.append("Hello, ");
sb.append("World!");
String result = sb.toString();
4 字符串替换
4.1 替换字符
String replaced = str1.replace('o', 'a'); // 替换所有 'o' 为 'a'
4.2 替换子字符串
String replacedStr = str1.replace("World", "Java");
4.3 使用正则表达式替换
String replacedAll = str1.replaceAll("\\d", "X"); // 将所有数字替换为 'X'
5 字符串拆分
5.1 使用 split()
方法
String[] words = str1.split(" "); // 按空格拆分字符串
6 字符串格式化
6.1 使用 String.format()
String formatted = String.format("Hello, %s! You have %d new messages.", "Alice", 5);
7 字符串检查
7.1 检查字符串是否以特定前缀开头:startsWith
boolean starts = str1.startsWith("Hello");
7.2 检查字符串是否以特定后缀结尾:endsWith
boolean ends = str1.endsWith("World!");
7.3 检查字符串是否包含特定子字符串:contains
boolean contains = str1.contains("World");
8 字符串的不可变性
8.1 不可变性概念
String str5 = "Hello";
str5 = str5.concat(", World!"); // 生成了新的字符串对象,原来的字符串对象未改变
8.2 使用 StringBuilder
处理可变字符串
StringBuilder sb = new StringBuilder("Hello");
sb.append(", World!"); // 对于大量字符串操作,使用 StringBuilder 可以提高性能
9 正则表达式与字符串处理
9.1 使用 matches()
方法
boolean isMatch = str1.matches("Hello,\\s\\w+!");
9.2 使用 split()
与正则表达式
String[] parts = "one,two,three".split(",");
9.3 使用 Pattern
和 Matcher
import java.util.regex.*;
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("abc123xyz");
while (matcher.find()) {
System.out.println(matcher.group());
}
10 字符串与基本类型的转换
10.1 字符串转基本类型
int num = Integer.parseInt("123");
double d = Double.parseDouble("3.14");
10.2 基本类型转字符串
String s = String.valueOf(123);
11 字符串与字符数组的转换
11.1 字符串转字符数组
char[] chars = str1.toCharArray();
11.2 字符数组转字符串
String str6 = new String(chars);