[c++] 문자열 검색

C++에서는 문자열을 검색하는 여러 가지 방법이 있습니다. 가장 간단한 방법은 find 함수를 사용하는 것입니다.

find 함수

find 함수는 문자열에서 특정 문자열 또는 문자를 찾는 기능을 제공합니다.

std::string str = "Hello, World!";
std::size_t found = str.find("World");
if (found != std::string::npos) {
    std::cout << "찾은 위치: " << found << std::endl;
} else {
    std::cout << "찾지 못함" << std::endl;
}

find_first_of 및 find_last_of 함수

find_first_offind_last_of 함수는 특정 문자의 첫 번째 또는 마지막 위치를 찾습니다.

std::string str = "apple orange banana";
std::size_t found = str.find_first_of("aeiou");
if (found != std::string::npos) {
    std::cout << "찾은 위치: " << found << std::endl;
} else {
    std::cout << "찾지 못함" << std::endl;
}

regex 라이브러리

C++11부터는 정규 표현식을 지원하는 내장 라이브러리인 <regex>가 있습니다. 이를 사용하여 더 복잡한 문자열 패턴을 검색할 수 있습니다.

#include <regex>
std::string str = "The quick brown fox jumps over the lazy dog";
std::regex pattern("\\b\\w{5}\\b");
std::smatch matches;
if (std::regex_search(str, matches, pattern)) {
    std::cout << "찾은 패턴: " << matches.str() << std::endl;
} else {
    std::cout << "찾지 못함" << std::endl;
}

Conclusion

C++에서는 문자열을 검색하기 위해 find, find_first_of, find_last_of, 또는 regex 라이브러리를 사용할 수 있습니다. 적합한 방법을 선택하여 문자열을 효과적으로 검색할 수 있습니다.