从一个完整的字符串之中查找子字符串的存在就属于字符串查找操作,在String类里面提供有如下几个查找方法:
- public boolean contains(String s)
判断此字符串是否存在。 - public int indexOf(String str)
从开头查找字符串的位置 - public int indexOf(String str,int fromIndex)
从指定位置查找字符串的位置 - public int lastIndexOf(String str)
由后向前查找指定字符串位置 - public int lastIndexOf(String s,int fromIndex)
从指定位置由后向前查找指定字符串 - public boolean startsWith(String prefix)
判断是否以指定的字符串开头 - public boolean startsWith(String prefix,int toffset)
由指定位置判断是否以指定的字符串开头 - public boolean endsWith(String suffix)
判断是否已指定字符串结束
class 测试
{
public static void main(String[] args)
{
String strA = "hellow";
String strB = "H";
System.out.println(strA.contains(strB));
}
}
此方法的操作相对而言比较直观一些,但是这个方法是从JDK1.5以后开始追加到程序之中的功能,在这之前一般通过indexOf()完成。
范例:
class 测试
{
public static void main(String[] args)
{
String strA = "hellow";
String strB = "H";
System.out.println(strA.indexOf(strB));
}
}
结果-1表示在此字符串中没有找到这个字符,如果是不是负数则表示该是字符的索引位置,它是由前向后查找的,也可以由后向前查找 : lastIndexOf()。
范例:
class 测试
{
public static void main(String[] args)
{
String strA = "hellow";
String strB = "w";
System.out.println(strA.lastIndexOf(strB));
}
}