1. indexOf() 方法:查找位置

indexOf() 方法用于在字符串中查找第一次出现指定字符或子字符串的索引(位置)

String str = "Hello, world!";

// 查找 'o' 第一次出现的位置
int index1 = str.indexOf('o');
System.out.println(index1); // 输出: 4 (因为 'o' 在 "Hello" 中是第4个位置)

// 查找 'z' 第一次出现的位置
int index2 = str.indexOf('z');
System.out.println(index2); // 输出: -1 (因为字符串中没有 'z')

b. 查找子字符串 (indexOf(String str))

String str = "Java programming is fun.";

// 查找 "program" 第一次出现的位置
int index1 = str.indexOf("program");
System.out.println(index1); // 输出: 5 (子字符串 "program" 从索引 5 开始)

// 查找 "Python"
int index2 = str.indexOf("Python");
System.out.println(index2); // 输出: -1 (未找到)

c. 从指定位置开始查找 (indexOf(String str, int fromIndex))

String str = "hello world, hello";

// 从索引 6 开始查找 "hello"
int index = str.indexOf("hello", 6);
System.out.println(index); // 输出: 13 (它跳过了第一个 "hello" 在索引 0 的匹配)

在这里虽然结果是从索引6的位置也就是world的w开始,但是总体index开始计数仍然是从第一个hello的h开始。

2. substring() 方法:提取子串

substring() 方法用于从一个字符串中提取出它的一部分,并返回一个新的字符串。

String str = "Welcome to Java!";

// 从索引 11 (包含 'J') 开始提取到字符串末尾
String sub1 = str.substring(11);
System.out.println(sub1); // 输出: "Java!"

b. 提取指定范围的子串 (substring(int beginIndex, int endIndex))
这是最常用的形式。它提取从 beginIndex包含)开始,到 endIndex不包含)结束的部分。

String str = "Hello, world!";

// 提取 "world"
// 'w' 的索引是 7
// '!' 的索引是 12 (我们想要在 'd' 后面停止,'d'的索引是11,所以结束索引是 11+1 = 12)
String sub2 = str.substring(7, 12);
System.out.println(sub2); // 输出: "world"

// 提取 "Hello"
String sub3 = str.substring(0, 5);
System.out.println(sub3); // 输出: "Hello"