1.boolean endsWith(String suffix)

测试此字符串是否以指定的后缀结束。

例子:

String str1 = "helloworld";
		boolean b1 = str1.endsWith("ld");
		System.out.println(b1);//true

运行结果:

true

2.boolean startsWith(String prefix)

测试此字符串是否以指定的前缀开始。

例子:

String str1 = "helloworld";
		boolean b2 = str1.startsWith("He");
		System.out.println(b2);//false

运行结果:

false

3.boolean startsWith(String prefix, int toffset)

测试此字符串从指定索引开始的子字符串是否以指定前缀开始。

例子:

String str1 = "helloworld";
		boolean b3 = str1.startsWith("ll",2);//从第三个位置开始判断前缀是否为"ll"
		System.out.println(b3);//true

运行结果:

true

4.boolean contains(CharSequence s)

当且仅当此字符串包含指定的 char 值序列时,返回 true。

例子:

String str1 = "helloworld";
		String str2 = "wo";
		System.out.println(str1.contains(str2));//true

运行结果:

true

5.int indexOf(String str)

返回指定子字符串在此字符串中第一次出现处的索引。

例子:

String str1 = "helloworld";
		System.out.println(str1.indexOf("lo"));//返回lo字符串第一次出现的索引
		//结果为3,若没有找到,则返回-1

运行结果:

3

6.int indexOf(String str, int fromIndex)

返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。

例子:

String str1 = "helloworld";
		System.out.println(str1.indexOf("lo",5));//从第6个字母w开始找字符串lo
		//结果找不到, 返回-1

运行结果:

-1

注:indexOf和lastIndexOf如果未找到相应的字符串,则返回-1

7.int lastIndexOf(String str)

返回指定子字符串在此字符串中最右边出现处的索引。

例子:

String str3 = "hellorworld";
		System.out.println(str3.lastIndexOf("or"));//or最右边出现处的索引

运行结果;

7

理解:字符串or在最右边出现处的索引为7,这个索引是从0开始算的,从左边数其实是第8个,但是这里的方法都是从0开始算的,数的时候不习惯可以先从1开始数,然后再减1即可。

8.int lastIndexOf(String str, int fromIndex)

返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。

例子:

String str3 = "hellorworld";
		System.out.println(str3.lastIndexOf("or", 6));//从第6个位置开始向左找

反向搜索的意思就是从右往左找,但是输出的索引还是从做向右数的
运行结果:

4

理解:从右往左数,在7的索引处也会搜索到or字符串,但是该方法是返回字符串从左向右数最后出现的索引,所以结果是4。
再次强调:输出的索引是从0开始计数的。

附加小问题:
什么情况下indexOf()和lastIndexOf()的返回值相同?
答:情况一:存在唯一的str,情况二:不存在str

9.String replace(char oldChar, char newChar)

返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。

例子:

String str1 = "北京欢迎您,北京欢迎您,北京欢迎您";
		String str2 = str1.replace('北', '东');//把字符串中所有的'北'都换成'东'
		
		System.out.println(str1);
		System.out.println(str2);

运行结果:

北京欢迎您,北京欢迎您,北京欢迎您
东京欢迎您,东京欢迎您,东京欢迎您

10. String replace(CharSequence target, CharSequence replacement)

使用指定的字面值替换序列替换此字符串所有匹配字面值目标序列的子字符串。

例子:

String str1 = "北京欢迎您,北京欢迎您,北京欢迎您";
		String str3 = str1.replace("北京", "上海");
		System.out.println(str3);

用一个字符序列替换字符串中的所有目标字符序列
运行结果:

上海欢迎您,上海欢迎您,上海欢迎您

11.split方法

在处理字符串的时候我们经常需要将他们切割,然后分别处理,比如我们有一个字符串:张三,李四,王五,赵六,现在我们想要将他们的名字拆分出来,变成一个单独的字符串,如何做呢?

使用split方法即可。

String str = "张三,李四,王五,赵六";
		String[] names = str.split(",");
		for (int i = 0; i < names.length; i++) {
    		System.out.println(names[i]);
		}

输出:

张三
李四
王五
赵六