2017-10-21 6 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의 코드 블록에서 사용 된 변수에 따라'lastIndex' 위치에서 검색을 시작하여'sentence'에서'word'의 첫 번째 항목을 찾습니다. – Adarsh

답변

0

sentence.indexOf(word,lastIndex);의 마지막 발견 occurance의 끝에서 serach을 시작하는 경우. 그렇지 않으면 -1

그것은 주어진 lastIndex

추가에서 코드의 주석을 시작 주어진 sentence에서 word를 검색합니다 반환합니다.

// 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 그런 다음 또 다른 반복을 할 것입니다 찾았지만 지정된 인덱스 lastIndex에서 시작하여, 문자열 word의 인덱스를 돌려 바로 word