strstr()

김민수·2025년 1월 9일

C++

목록 보기
50/68

strstr()<cstring> 헤더에 포함된 함수로, 문자열을 처리할 때, 특정 문자열이 다른 문자열에 포함되어 있는지를 확인할 때 strstr() 함수를 사용한다. 이 함수는 C 스타일 문자열(null-terminated string)에서 부분 문자열(substring)을 찾는 함수다.


1. 정의

strstr()는 특정 문자열 내에서 원하는 부분 문자열이 첫 번째로 나타나는 위치를 반환한다.

char* strstr(const char* haystack, const char* needle);
  • haystack: 검색 대상 문자열 (전체 문자열)
  • needle: 찾고자 하는 부분 문자열
  • 반환값:
    • 부분 문자열이 발견되면 해당 부분 문자열이 시작하는 위치의 포인터를 반환한다.
    • 부분 문자열이 없으면 nullptr을 반환한다.


2. 동작 방식

  • strstr()haystack 문자열 내에서 needle 문자열이 처음 나타나는 위치를 탐색한다.
  • 만약 needle 문자열이 빈 문자열("")인 경우, haystack의 시작 위치를 반환한다.
  • needlehaystack에 포함되지 않으면 nullptr을 반환한다.


3. 사용 예시

부분 문자열 찾기

#include <iostream>
#include <cstring>

int main() {
    const char* haystack = "Hello, world!";
    const char* needle = "world";

    char* result = strstr(haystack, needle);

    if (result != nullptr) {
        std::cout << "Found substring: " << result << std::endl;
    } else {
        std::cout << "Substring not found." << std::endl;
    }

    return 0;
}

출력:

Found substring: world!
  • strstr()"Hello, world!"에서 "world"를 찾아 해당 부분 문자열이 시작하는 위치를 반환한다.
  • 결과적으로 "world!"가 출력된다.

부분 문자열 이후의 내용 출력

strstr()가 반환하는 포인터는 부분 문자열이 시작하는 위치를 가리키므로, 반환된 포인터를 통해 이후의 문자열을 처리할 수 있다.

#include <iostream>
#include <cstring>

int main() {
    const char* haystack = "This is a sample string";
    const char* needle = "sample";

    char* result = strstr(haystack, needle);

    if (result != nullptr) {
        std::cout << "Substring found at position: " 
                  << (result - haystack) << std::endl;
    } else {
        std::cout << "Substring not found." << std::endl;
    }

    return 0;
}

출력:

Substring found at position: 10
  • result - haystack을 통해 부분 문자열이 시작하는 인덱스 위치를 구할 수 있다.

대소문자 무시하고 문자열 찾기

기본적으로 strstr()는 대소문자를 구분하여 검색하지만, 대소문자를 구분하지 않고 검색하려면 문자열을 소문자 또는 대문자로 변환한 후 strstr()를 호출해야 한다.

#include <iostream>
#include <cstring>
#include <cctype>

// 문자열을 소문자로 변환하는 함수
void toLowerCase(char* str) {
    while (*str) {
        *str = std::tolower(*str);
        ++str;
    }
}

int main() {
    char haystack[] = "C++ Programming is Fun";
    char needle[] = "programming";

    // 원본 문자열 복사 후 소문자로 변환
    char lowerHaystack[100], lowerNeedle[100];
    strcpy(lowerHaystack, haystack);
    strcpy(lowerNeedle, needle);
    toLowerCase(lowerHaystack);
    toLowerCase(lowerNeedle);

    char* result = strstr(lowerHaystack, lowerNeedle);

    if (result != nullptr) {
        std::cout << "Substring found: " << haystack + (result - lowerHaystack) << std::endl;
    } else {
        std::cout << "Substring not found." << std::endl;
    }

    return 0;
}


4. 예외 및 주의사항

  1. 대소문자 구분
    strstr()는 대소문자를 구분하여 검색한다.
    예를 들어, "Hello""hello"는 서로 다른 문자열로 취급된다.

  2. null-terminated 문자열
    strstr()null-terminated 문자열(C 스타일 문자열)에서만 동작한다.
    C++ std::string 객체와 함께 사용하려면 c_str() 멤버 함수를 통해 C 스타일 문자열로 변환해야 한다.

std::string과 함께 사용

#include <iostream>
#include <cstring>
#include <string>

int main() {
    std::string haystack = "C++ programming is fun";
    std::string needle = "programming";

    char* result = strstr(haystack.c_str(), needle.c_str());

    if (result != nullptr) {
        std::cout << "Found substring: " << result << std::endl;
    } else {
        std::cout << "Substring not found." << std::endl;
    }

    return 0;
}
profile
안녕하세요

0개의 댓글