字符串和子字符串以及子字符串在主字符串中出现的次数

房车苏尼思

我在谷歌的一些解决方案的帮助下编写了代码。你能帮我详细说明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();

努坦

sentence.indexOf(word,lastIndex);返回 string 的索引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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章