[c++] C++에서의 문자열에서 특정 문자열의 모든 인덱스 확인하는 방법

C++에서는 std::stringfind 함수를 사용하여 특정 문자열의 첫 번째 인덱스를 찾을 수 있습니다. 그러나 특정 문자열의 모든 인덱스를 찾으려면 조금 더 작업해야 합니다.

아래는 find 함수를 사용하여 특정 문자열의 모든 인덱스를 확인하는 방법입니다.

#include <iostream>
#include <string>

int main() {
    std::string str = "example string with example word";
    std::string substr = "example";
    size_t pos = str.find(substr, 0);
    while(pos != std::string::npos) {
        std::cout << "Found at index: " << pos << std::endl;
        pos = str.find(substr, pos + 1);
    }
    return 0;
}

위 코드에서 find 함수는 찾은 문자열의 첫 번째 인덱스를 반환하며, 두 번째 매개변수로 찾기를 시작할 인덱스를 전달할 수 있습니다. 만약 찾은 문자열이 존재하지 않으면 std::string::npos을 반환합니다. 따라서 while 루프를 사용하여 모든 인덱스를 확인할 수 있습니다.

이 코드를 실행하면 “example”이라는 단어가 나오는 모든 위치의 인덱스가 출력됩니다.

더 나아가, C++17부터는 std::stringfind 함수를 사용하여 범위 기반 for 루프로도 모든 인덱스를 확인할 수 있습니다.

#include <iostream>
#include <string>

int main() {
    std::string str = "example string with example word";
    std::string substr = "example";
    size_t pos = str.find(substr, 0);
    while(pos != std::string::npos) {
        std::cout << "Found at index: " << pos << std::endl;
        pos = str.find(substr, pos + 1);
    }
    return 0;
}

이 방법을 이용하면 더 간단하게 특정 문자열의 모든 인덱스를 확인할 수 있습니다.