如何在 Java 中檢查特定字串在另一個字串中出現多次?
您可以使用以下任何方法查詢字串是否包含指定的字元序列:
indexOf() 方法 - String 類的 indexOf() 方法接受一個字串值,並在當前字串中查詢其(起始)索引並返回它。如果在當前字串中找不到給定字串,則此方法返回 -1。
contains() 方法 - String 類的 contains() 方法接受一個字元序列值,並驗證它是否存在於當前字串中。如果找到則返回 true,否則返回 false。
除此之外,您還可以使用 String 類的 Split() 方法。此方法接受一個表示分隔符的字串值,根據給定的分隔符拆分當前字串,並返回一個包含字串標記的字串陣列。
您可以使用此方法將字串拆分為一個單詞陣列,並手動將每個單詞與所需單詞進行比較。
示例
以下 Java 示例將檔案內容讀取到一個字串中,從使用者那裡接受一個單詞,並列印該單詞在字串(檔案)中出現的次數。
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Scanner; public class StringOccurrence { public static String fileToString(String filePath){ Scanner sc = null; String input = null; StringBuffer sb = null; try { sc = new Scanner(new File(filePath)); sb = new StringBuffer(); while (sc.hasNextLine()) { input = sc.nextLine(); sb.append(" "+input); } } catch(Exception ex) { ex.toString(); } System.out.println("Contents of the file: "); System.out.println(sb); return sb.toString(); } public static void main(String args[]) throws FileNotFoundException { //Reading the word to be found from the user String filePath = "D://sampleData.txt"; Scanner sc = new Scanner(System.in); System.out.println("Enter the word to be found"); String word = sc.next(); boolean flag = false; int count = 0; String text = fileToString(filePath); String textArray[] = text.split(" "); for(int i=0; i<textArray.length; i++) { if(textArray[i].equals(word)) { flag = true; count = count+1; } } if(flag) { System.out.println("Number of occurrences is: "+count); } else { System.out.println("File does not contain the specified word"); } } }
輸出
Enter the word to be found Readers Contents of the file: Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. The journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated, we worked our way to adding fresh tutorials to our repository which now proudly flaunts a wealth of tutorials and allied articles on topics ranging from programming languages to web designing to academics and much more. 40 million readers read 100 million pages every month. Our content and resources are freely available and we prefer to keep it that way to encourage our readers acquire as many skills as they would like to. We don’t force our readers to sign up with us or submit their details either. No preconditions and no impediments. Simply Easy Learning! Number of occurrences is: 4
廣告