문자열 myString과 pat이 주어집니다. myString에서 pat이 등장하는 횟수를 return 하는 solution 함수를 완성해 주세요.
function solution(myString, pat) {
let count = 0;
let startIndex = 0;
while (true) {
startIndex = myString.indexOf(pat, startIndex);
if (startIndex === -1) break;
count++;
startIndex++;
}
return count;
}
const myString = "banana";
const pat = "ana";
startIndex = myString.indexOf(pat, startIndex);
startIndex인 0번 인덱스부터 찾는다."b[ana]na"startIndex는 1이 된다.if (startIndex === -1) break;
count++;
startIndex++;
startIndex가 -1이 아니라면 과정을 다시 반복한다.startIndex === -1 : 해당하는 인덱스를 찾지 못했다.startIndex !== -1 : 해당하는 인덱스를 찾았다.count는 1이 된다.startIndex는 2가 된다.startIndex = myString.indexOf(pat, startIndex);
startIndex인 2번 인덱스부터 다시 찾는다."ban[ana]"if (startIndex === -1) break;
count++;
startIndex++;
startIndex가 -1이 아니기 때문에 과정을 다시 반복한다.count는 2가 된다.startIndex는 4가 된다.startIndex = myString.indexOf(pat, startIndex);
startIndex인 4번 인덱스부터 찾는다.indexOf는 -1을 반환한다.if (startIndex === -1) break;
startIndex가 -1이 되었으므로 반복문은 종료된다.return count;
count의 현재 값인 2가 반환된다.따라서, 결과는 다음과 같다.
solution("banana", "ana"); // 2