一、indexOf() 方法
1、indexOf() 方法是 Java 中最常用的字符串查找方法之一。它的作用是在源字符串中查找子串,如果找到,则返回子串的起始位置,否则返回 -1。
2、indexOf() 方法有两种形式,一种是指定要查找的字符串,另一种是指定要查找的字符。下面是这两种形式的语法:
public int indexOf(String str)
public int indexOf(int ch)
3、下面是一个使用 indexOf() 方法查找子串的示例:
String str = "hello world";
int index = str.indexOf("wor");
System.out.println(index);
4、上述代码将输出:
6
表示在字符串 "hello world" 中,子串 "wor" 起始位置为 6。
5、需要注意的是,indexOf() 方法只会找到第一个匹配的子串,如果要查找所有匹配的子串,则需要使用 lastIndexOf() 方法。
二、contains() 方法
1、contains() 方法是 String 类中的方法,该方法可以判断一个字符串中是否包含指定的子字符串,如果包含,返回 true;否则返回 false。
2、该方法的语法如下:
public boolean contains(CharSequence s)
3、下面是一个使用 contains() 方法查找子串的示例:
String str = "hello world";
boolean result = str.contains("wor");
System.out.println(result);
4、上述代码将输出:
true
5、需要注意的是,contains() 方法将区分大小写,如果要不区分大小写,则可以使用 toLowerCase() 或 toUpperCase() 方法将字符串转为小/大写字母再进行查找。
三、startsWith() 方法和 endsWith() 方法
1、startsWith() 方法用于判断一个字符串是否以指定的前缀开始,如果是,返回 true;否则返回 false。
2、endsWith() 方法用于判断一个字符串是否以指定的后缀结束,如果是,返回 true;否则返回 false。
3、这两个方法的语法如下:
public boolean startsWith(String prefix)
public boolean endsWith(String suffix)
4、下面是一个使用 startsWith() 方法和 endsWith() 方法查找前后缀的示例:
String str = "hello world";
boolean prefixResult = str.startsWith("he");
boolean suffixResult = str.endsWith("ld");
System.out.println(prefixResult);
System.out.println(suffixResult);
5、上述代码将输出:
true
true
6、需要注意的是,这两个方法同样区分大小写,如果要不区分大小写,则需要转为小/大写字母再进行查找。
四、StringTokenizer 类
1、StringTokenizer 类可以将一个字符串按照指定分隔符进行分割,生成多个子串。每个子串都可以单独处理。
2、StringTokenizer 类的语法如下:
public class StringTokenizer
extends Object
implements Enumeration<Object>
3、下面是一个使用 StringTokenizer 类分割字符串的示例:
String str = "hello,world";
StringTokenizer tokenizer = new StringTokenizer(str, ",");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
System.out.println(token);
}
4、上述代码将输出:
hello
world
5、需要注意的是,StringTokenizer 类默认是以空格、制表符、换行符等作为分隔符的,如果要分隔其他字符,则需要指定分隔符。
五、正则表达式
1、正则表达式是一种描述字符串模式的语言,可以用来匹配字符串、替换字符串、分割字符串等。
2、Java 中的正则表达式主要用到 Pattern 类和 Matcher 类。
3、下面是一个使用 Pattern 类和 Matcher 类匹配字符串的示例:
String str = "hello world";
Pattern pattern = Pattern.compile("wor");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
System.out.println(start);
System.out.println(end);
}
4、上述代码将输出:
6
9
5、需要注意的是,正则表达式相对较为复杂,需要花费一定时间去学习和掌握。
原创文章,作者:OFOBD,如若转载,请注明出处:https://www.506064.com/n/372812.html
微信扫一扫
支付宝扫一扫