
5.3 提取字符串信息
字符串作为对象,可以通过String中的方法获取其有效信息,如获取某字符串的长度、某个索引位置的字符等。
5.3.1 获取字符串长度
使用length()方法可以获取字符串的长度,长度指的是字符串中字符的个数,其中空格也是长度的一部分,语法格式如下:
str.length();
例如,定义一个字符串str,使用length()方法获取其长度,代码如下:
String str="I Love Java!" int size=str.length();
将size输出,得出的结果就是12。
这里length()方法的返回值是int型,所以需要一个int型变量来保存结果。
【例5.6】创建一个字符串,获取它的长度并输出(源代码\ch05\5.6.txt)。

运行结果如图5-6所示。

图5-6 获取字符串的长度
5.3.2 获取指定位置的字符
使用charAt()方法可以获取指定位置的字符,语法格式如下:
str.charAt(index)
参数介绍如下:
· str:任意字符串对象。
· index:char值的索引。
【例5.7】创建一个字符串,找出字符串中索引位置为4的字符(源代码\ch05\5.7.txt)。

运行结果如图5-7所示。

图5-7 获取指定位置的字符
5.3.3 获取子字符串索引位置
indexOf()方法返回的是搜索的字符或字符串在字符串中首次出现的索引位置,如果没有检索到要查找的字符或字符串,则返回-1,语法格式如下:
str.indexOf(substr);
参数介绍如下:
· str:任意字符串对象。
· substr:要搜索的字符或字符串。
例如:查找字符e在字符串s中首次出现的索引位置,代码如下:
String s = "hello world"; //声明字符串 int size=s. indexOf('e');
这里返回的结果为:
1
lastIndexOf()方法返回的是搜索的字符或字符串在字符串中最后一次出现的索引位置,如果没有检索到要查找的字符或字符串,则返回-1,语法格式如下:
str. lastindexOf(substr);
参数介绍如下:
· str:任意字符串对象。
· substr:要搜索的字符或字符串。
例如:查找字符o在字符串s中最后一次出现的索引位置,代码如下:
String s = "hello world"; //声明字符串 int size=s. lastindexOf('o');
这里返回的结果为7。
☆大牛提醒☆
空格也算一个字符长度。
【例5.8】创建一个字符串,找出字符o在该字符串首次出现的索引值和最后一次出现的索引值(源代码\ch05\5.8.txt)。

运行结果如图5-8所示。

图5-8 获取子字符串索引位置
5.3.4 判断字符串首尾内容
startsWith()方法和endsWith()方法分别用于判断字符串是否以指定的内容开始或结束。这两个方法的返回值都是boolean类型。
1.startsWith(String prefix)方法
该方法用于判断字符串是否以指定的前缀开始。语法格式如下:
str.startsWith(prefix)
参数介绍如下:
· str:任意字符串对象。
· prefix:作为前缀的字符串。
【例5.9】查找学生中姓“王”的同学(源代码\ch05\5.9.txt)。

运行结果如图5-9所示。

图5-9 查找姓王的同学
2.endsWith(String suffix)方法
该方法用于判断字符串是否以指定的后缀结束。语法格式如下:
s tr.endsWith(suffix)
参数介绍如下:
· str:任意字符串对象。
· suffix:作为后缀的字符串。
【例5.10】在成语集合中查找以“春”结束的成语并展示出来(源代码\ch05\5.10.txt)。

运行结果如图5-10所示。

图5-10 查找以“春”结束的成语
5.3.5 判断子字符串是否存在
contains()方法可以判断字符串中是否包含指定的内容,语法格式如下:
str. contains (string);
参数介绍如下:
· str:任意字符串对象。
· string:查询的子字符串。
【例5.11】搜索歌名部分关键词来找歌曲(源代码\ch05\5.11.txt)。

运行结果如图5-11所示。

图5-11 通过关键字搜索歌曲
5.3.6 获取字符数组
通过toCharArray()方法可以将一个字符串转换为一个字符数组。语法格式如下:
str. toCharArray( );
参数介绍如下:
· str:任意字符串对象。
【例5.12】以数组方式输出古诗内容(源代码\ch05\5.12.txt)。

运行结果如图5-12所示。

图5-12 以数组方式输出古诗