Java字符串搜索

来源:互联网 发布:淘宝转运香港 编辑:程序博客网 时间:2024/05/21 10:34

可以使用indexOf()lastIndexOf()方法获取一个字符或字符串在另外一个字符串中的的索引。例如,

public class Main {  public static void main(String[] args) {    String str = new String("Apple");    int index = str.indexOf('p'); // index will have a value of 1    System.out.println(index);    index = str.indexOf("pl"); // index will have a value of 2    System.out.println(index);    index = str.lastIndexOf('p'); // index will have a value of 2    System.out.println(index);    index = str.lastIndexOf("pl"); // index will have a value of 2    System.out.println(index);    index = str.indexOf("k"); // index will have a value of -1    System.out.println(index);  }}
Java

上面的代码生成以下结果。

1222-1
Java

indexOf()方法从字符串的开头开始搜索字符或字符串,并返回第一个匹配的索引。lastIndexOf()方法从末尾开始逆向匹配字符或字符串,并返回第一个匹配的索引。如果在字符串中没有找到字符或字符串,这些方法返回-1

匹配字符串的开始和结束

startsWith()检查字符串是否以指定的参数开头,而endsWith()检查字符串是否以指定的字符串参数结尾。
两个方法都返回一个布尔值。

public class Main {  public static void main(String[] args) {    String str = "This is a test";    // Test str, if it starts with "This"    if (str.startsWith("This")) {      System.out.println("String starts with  This");    } else {      System.out.println("String does  not  start with  This");    }    // Test str, if it ends with "program"    if (str.endsWith("program")) {      System.out.println("String ends  with  program");    } else {      System.out.println("String does  not  end  with  program");    }  }}
Java

上面的代码生成以下结果。

String starts with  ThisString does  not  end  with  program
0 0
原创粉丝点击