如何在另一个字符串中搜索字符串

时间:2015-12-07 23:15:34

标签: java string

我正在尝试创建一个程序,该程序能够在用户的输入字符串中搜索特定单词,并计算该单词重复的次数。

例如,我希望程序的运行方式如下:

  

请输入您选择的字符串:

     

基洛纳是一个不错的城市,基洛纳是我的家。

     

输入您要搜索的字词:

     

基洛纳

     

基洛纳这个词被发现了2次。

我该怎么做呢?我最初的方法是使用循环,但这并没有让我走得太远。

这是我到目前为止所做的:

import java.util.Scanner;

public class FinalPracc {
    public static void main(String[] args) {
        Scanner s1 = new Scanner(System.in);
        System.out.println("please enter a string of you choice: ");
        String a = s1.nextLine();
        System.out.println("Please enter the word you would like to search for: ");
        String b = s1.nextLine();

        int aa = a.length();
        int bb = b.length();

        if (a.contains(b)) {
            System.out.println("word found");
            int c = a.indexOf(b);
            int
            if (
        }
    }
    /* ADD YOUR CODE HERE */
}

2 个答案:

答案 0 :(得分:3)

一种方法是,如果您找到该单词,请修改搜索字符串以删除包含该单词之前的所有内容,然后再次搜索:

public static void main(String[] args) { 

    Scanner s1=new Scanner(System.in);
    System.out.println("please enter a string of you choice: ");
    String a=s1.nextLine();
    System.out.println("Please enter the word you would like to search for: ");
    String b=s1.nextLine();

    int count = 0;
    while(b.contains(a)) {
        count++;
        int pos = b.indexOf(a);
        b = b.substring(pos + a.length());
    }

    if (count > 0){
        System.out.println("word found " + count + " times");
    } else {
        System.out.println("word not found");
    }
}

编辑:或者,如果您不想在循环中调用substring,则可以使用indexOf的形式,该形式为搜索提供起始索引。在这种情况下,您的循环可能如下所示:

    int count = 0;
    int searchIndex = 0;
    while((searchIndex = b.indexOf(a, searchIndex)) > -1) {
        count++;
        searchIndex += a.length();
    }

答案 1 :(得分:1)

也许像while(a.contains(b)) 并且每次找到一个单词时将其设置为一个计数器并将所有单词切割为每个循环轮次中找到的单词的最后一个符号。