一、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/zh-tw/n/372812.html