如何在 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

更新于: 2019年9月10日

3K+ 次查看

启动您的 职业生涯

通过完成课程获得认证

开始
广告