strstr()는 <cstring> 헤더에 포함된 함수로, 문자열을 처리할 때, 특정 문자열이 다른 문자열에 포함되어 있는지를 확인할 때 strstr() 함수를 사용한다. 이 함수는 C 스타일 문자열(null-terminated string)에서 부분 문자열(substring)을 찾는 함수다.
strstr()는 특정 문자열 내에서 원하는 부분 문자열이 첫 번째로 나타나는 위치를 반환한다.
char* strstr(const char* haystack, const char* needle);
haystack: 검색 대상 문자열 (전체 문자열)needle: 찾고자 하는 부분 문자열nullptr을 반환한다.strstr()는 haystack 문자열 내에서 needle 문자열이 처음 나타나는 위치를 탐색한다.needle 문자열이 빈 문자열("")인 경우, haystack의 시작 위치를 반환한다.needle이 haystack에 포함되지 않으면 nullptr을 반환한다.#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;
}
대소문자 구분
strstr()는 대소문자를 구분하여 검색한다.
예를 들어, "Hello"와 "hello"는 서로 다른 문자열로 취급된다.
null-terminated 문자열
strstr()는 null-terminated 문자열(C 스타일 문자열)에서만 동작한다.
C++ std::string 객체와 함께 사용하려면 c_str() 멤버 함수를 통해 C 스타일 문자열로 변환해야 한다.
#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;
}