문자열 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