课时52:字符串查找
从一个完整的字符串之中查找子字符串的存在就属于字符串查找操作,在 String 类里面
提供几个参考方法:
方法名称。
public public boolean contains(String s)//判断子字符串是否存在(1.5版本之后才存在); public int indexOf(String str)//从头查找指定字符串的位置,找不到返回-1; public int indexOf(String str.int fromIndex).//从指定位置查找指定字符串的位置; public int lastIndexOf(String str).//由后向前查找指定字符串的位置; public int lastIndexOf(String str.int fromIndex).//从指定位置由后向前查找指定字符串的位置; public boolean startsWith(String prefix).//判断是否以指定的字符串开头; public boolean startsWith(String prefix, int toffset).//由指定位置判断是否以指定的字符串开头; public boolean endsWith(String suffix).//判断是否以指定的字符串结尾。
范例:判断子字符串是否存在(精简的过程)
public class StringDemo { I public static void main(String args[]){ String str = "www.mldn.cn" ; System.out.println(str.contains("mldn")) ; // true, System.out.println(str.contains("hello")) ; // false } }
此方法的操作直观,但是是从 JDK 1.5之后开始追加到程序之中的功能,在 JDK1.5之前,如果要进行数据的查询只能依靠 IndexOf()的方法来完成
范例:判断子字符串是否存在
public classstringDemo { public static void main(String args[ ] ) { String str = "www.mldn.cn" ; System.out.println(str.index0f("mldn")) ; System.out.println(str.index0f("hello")); // -1 if (str.indexOf("mldn")|!= -1) { system.out.println("数据存在。"); } } }
4: 表示在mldn在第四个开始位置;
-1:表示没有查到。
IndexOf()是为了进行子字符串位置的查询,在一些开发之中就可以用此形式来进行一些索引的确定。IndexOf() 是由前向后查找的,也可以由后向前查找。
范例:使用 LastIndexOf() 查找
public class StringDemo { Public statie void main(String args[]) { String str= "www.mldn.cn’ Svstem.out.println(str lastIndexOf(". ")),. } }
这些方法都进行了重载,从第五个开始查:
主要能确认程序数据的位置,在进行字符串查找的时候也需要判断开头或结尾的操作。
范例:判断是否已指定的字符串开头或结尾(后面的许多设计都需要它的支持)
public class stringDemo{ public static void main(string args[ ]) { String ste = “**@@www.mldn.cn##” System.out.println(str.startswith( “**”)) System.out.println(str.startswith( “##”)) } }
从第二个开始, System.out.println(str.startswith( “@@”,2)),开头和结尾很容易,但后面开发离不开它,查找位置的操作对我们至关重要。