字符串和子字符串以及主字符串中存在多少次子字符串

时间:2017-10-21 11:38:55

标签: java string substring

我已经借助谷歌的一些解决方案编写了代码。你能帮我详细介绍一下while循环的作用吗?

import java.util.Scanner;

public class TwoStringsWordRepeat {
    public static void main(String[] args) {
        Scanner s = new Scanner (System.in);
        System.out.print("Enter Sentence: ");
        String sentence = s.nextLine();
        System.out.print("Enter word: ");
        String word = s.nextLine();
        int lastIndex = 0;
        int count = 0;
        while (lastIndex != -1) {
            lastIndex = sentence.indexOf(word, lastIndex);
            if (lastIndex != -1) {
                count++;
                lastIndex += word.length();
            }
        }
        System.out.println(count);
    }
}

解释while循环.indexOf();中的代码。

2 个答案:

答案 0 :(得分:0)

indexOf()返回搜索字符串中给定子字符串第一次出现的偏移量,如果找不到相应的字符串,则返回-1

使用替代语法,可以在给定的偏移量处开始搜索,因此它只会在该特定的起始偏移量之后找到匹配项。

如果找到了word,那么它将进行另一次迭代,但是在word

的最后一次发现结束时开始搜索

答案 1 :(得分:0)

sentence.indexOf(word,lastIndex);从指定的索引word开始,返回字符串lastIndex的索引。否则将返回-1

它会从给定word

开始搜索给定sentence中的lastIndex

在代码中添加了注释。

// While we are getting the word in the sentence
// i.e while it is not returning -1
while(lastIndex != -1) {
    // Will get the last index of the searched word
    lastIndex = sentence.indexOf(word, lastIndex);

    // Will check whether word found or not 
    if(lastIndex != -1) {
        // If found will increment the word count
        count++;
        // Increment the lastIndex by the word lenght
        lastIndex += word.length();
    }
}

// Print the count
System.out.println(count);