java字符串查找的形式有哪些

avatar
作者
猴君
阅读量:0

在Java中字符串查找的形式有以下几种:

  1. 使用indexOf()方法:该方法返回指定子字符串第一次出现的索引,如果未找到则返回-1。

例如:

String str = "Hello, world!"; int index = str.indexOf("world"); System.out.println(index); // 输出6 
  1. 使用lastIndexOf()方法:该方法返回指定子字符串最后一次出现的索引,如果未找到则返回-1。

例如:

String str = "Hello, world!"; int index = str.lastIndexOf("o"); System.out.println(index); // 输出8 
  1. 使用contains()方法:该方法用于判断字符串中是否包含指定的子字符串,返回true或false。

例如:

String str = "Hello, world!"; boolean contains = str.contains("world"); System.out.println(contains); // 输出true 
  1. 使用matches()方法:该方法用于判断字符串是否匹配指定的正则表达式。

例如:

String str = "Hello, world!"; boolean isMatch = str.matches("Hello.*"); System.out.println(isMatch); // 输出true 
  1. 使用startsWith()和endsWith()方法:这两个方法分别用于判断字符串是否以指定的前缀开始或以指定的后缀结束,返回true或false。

例如:

String str = "Hello, world!"; boolean startsWith = str.startsWith("Hello"); boolean endsWith = str.endsWith("world!"); System.out.println(startsWith); // 输出true System.out.println(endsWith); // 输出true 

这些方法可以根据具体的需求选择合适的方式进行字符串查找。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!