codecamp

Java 字符串搜索

Java数据类型教程 - Java字符串搜索


我们可以使用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);
  }
}

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

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 字符串字符
Java 子字符串
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

Java 数据类型介绍

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }