C/C++에서 std::strstr()은 문자열 일치에 사용되는 미리 정의된 함수입니다. 문자열 함수에 필요한 헤더 파일입니다. 이 함수는 두 개의 문자열을 사용합니다 s1 그리고 s2 인수로 사용하고 문자열이 처음 나타나는 것을 찾습니다. s2 문자열에 s1 . 일치 과정에는 종료 널 문자(' ')가 포함되지 않지만 함수는 거기서 멈춥니다.
통사론
char * strstr (const char * s1 , const char * s2 );>
매개변수
- s1 : 검사할 기본 문자열입니다. s2 : 문자열에서 검색할 하위 문자열입니다.
반환 값
- 이 함수는 발견된 문자의 첫 번째 문자에 대한 포인터 포인트를 반환합니다. s2 ~에 s1 그렇지 않으면 널 포인터인 경우 s2 에 존재하지 않습니다 s1 .
- s2가 빈 문자열을 가리키는 경우 s1이 반환됩니다.
예
아래 프로그램은 strstr() 함수의 사용법을 보여줍니다.
씨
// C program to illustrate strstr()> #include> #include> int> main()> {> >// Take any two strings> >char> s1[] =>'techcodeview.com'>;> >char> s2[] =>'for'>;> >char>* p;> >// Find first occurrence of s2 in s1> >p =>strstr>(s1, s2);> >// Prints the result> >if> (p) {> >printf>(>'String found
'>);> >printf>(>'First occurrence of string '%s' in '%s' is '> >''%s''>,> >s2, s1, p);> >}> >else> >printf>(>'String not found
'>);> >return> 0;> }> |
>
>
C++
// CPP program to illustrate strstr()> #include> #include> using> namespace> std;> int> main()> {> >// Take any two strings> >char> s1[] =>'techcodeview.com'>;> >char> s2[] =>'for'>;> >char>* p;> >// Find first occurrence of s2 in s1> >p =>strstr>(s1, s2);> >// Prints the result> >if> (p) {> >cout <<>'String found'> << endl;> >cout <<>'First occurrence of string ''> << s2> ><<>'' in ''> << s1 <<>'' is ''> << p <<>'''> ><< endl;> >}> >else> {> >cout <<>'String not found'> << endl;> >}> >return> 0;> }> |
>
>산출
String found First occurrence of string 'for' in 'techcodeview.com' is 'forGeeks'>
시간 복잡도: O(n + m), 여기서 n은 s1의 크기이고 m은 s2의 크기입니다.
보조 공간: O(m), 여기서 m은 s2의 크기입니다.
메모: strstr()의 공식 구현은 지정되지 않으며, 구현은 표준 문자열 일치 알고리즘 중 하나로 구성되는 것으로 가정됩니다. 여기서는 위에서 언급한 바와 같이 시간 및 공간 복잡도를 갖는 Knuth-Morris-Pratt 알고리즘을 사용하여 구현한다고 가정하였다.
애플리케이션 : 문자열을 다른 문자열로 교체
이 예에서는 strstr() 함수를 사용하여 먼저 하위 문자열의 발생을 검색합니다. STL ~에 s1 그 후에는 해당 단어를 다음으로 바꿉니다. 문자열 .
C++
// CPP program to illustrate strstr()> #include> #include> using> namespace> std;> int> main()> {> >// Take any two strings> >char> s1[] =>'Fun with STL'>;> >char> s2[] =>'STL'>;> >char>* p;> >// Find first occurrence of s2 in s1> >p =>strstr>(s1, s2);> >// Prints the result> >if> (p) {> >strcpy>(p,>'Strings'>);> >cout << s1;> >}> >else> {> >cout <<>'String not found'> << endl;> >}> >return> 0;> }> |
>
>
씨
// C program to illustrate strstr()> #include> #include> int> main()> {> >// Take any two strings> >char> s1[] =>'Fun with STL'>;> >char> s2[] =>'STL'>;> >char>* p;> >// Find first occurrence of s2 in s1> >p =>strstr>(s1, s2);> >// Prints the result> >if> (p) {> >strcpy>(p,>'Strings'>);> >printf>(>'%s'>, s1);> >}> >else> >printf>(>'String not found
'>);> >return> 0;> }> |
>
오토캐드 늘이기 명령
>산출
Fun with Strings>
시간 복잡도: O(n + m), 여기서 n은 s1의 크기이고 m은 s2의 크기입니다.
보조 공간: O(m), 여기서 m은 s2의 크기입니다.