菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻

Java 字符串搜索

原创
05/13 14:22 更新

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);
  }
}

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

图片.png

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");
    }
  }
}

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

图片.png

综合评分:9.9 评分 请对本文进行纠错,及学习过程中有困难疑惑可在此进行讨论