在Java中字符串查找的形式有以下几种:
- 使用indexOf()方法:该方法返回指定子字符串第一次出现的索引,如果未找到则返回-1。
例如:
String str = "Hello, world!"; int index = str.indexOf("world"); System.out.println(index); // 输出6
- 使用lastIndexOf()方法:该方法返回指定子字符串最后一次出现的索引,如果未找到则返回-1。
例如:
String str = "Hello, world!"; int index = str.lastIndexOf("o"); System.out.println(index); // 输出8
- 使用contains()方法:该方法用于判断字符串中是否包含指定的子字符串,返回true或false。
例如:
String str = "Hello, world!"; boolean contains = str.contains("world"); System.out.println(contains); // 输出true
- 使用matches()方法:该方法用于判断字符串是否匹配指定的正则表达式。
例如:
String str = "Hello, world!"; boolean isMatch = str.matches("Hello.*"); System.out.println(isMatch); // 输出true
- 使用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
这些方法可以根据具体的需求选择合适的方式进行字符串查找。