2017-10-21 142 views
0

我已经通过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();

+0

indexOf()根据在urs的代码块中使用的变量,在'sentence'中找到'word'的第一个匹配项,在'lastIndex'位置开始搜索。 – Adarsh

回答

0

sentence.indexOf(word,lastIndex);最后发现次数结束返回字符串word的索引,从指定的索引lastIndex开始。否则将返回-1

它将搜索在给定的sentenceword给出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); 
0

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

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

如果word已经找到,那么它会做另一次迭代,但开始检索算法权在word