繁体   English   中英

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

[英]String and substring and how many times substring present in main string

我已经借助Google的某些解决方案编写了代码。 您能帮我详细了解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();

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

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

如果找到了word那么它将进行另一次迭代,但是会在最后一次出现word的末尾开始搜索

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

它将从给定的lastIndex开始搜索给定sentenceword

在代码中添加了注释。

// 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM