Computer >> 컴퓨터 >  >> 프로그램 작성 >> C 프로그래밍

C 언어에서 strstr() 함수란 무엇입니까?

<시간/>

C 라이브러리 함수 char *str(const char *haystack, const char *needle) 함수는 하위 문자열 needle의 첫 번째 발생을 찾습니다. haystack 문자열에서 . 종료 '\0' 문자는 비교되지 않습니다.

문자 배열을 문자열이라고 합니다.

선언

배열을 선언하는 구문은 다음과 같습니다 -

char stringname [size];

예를 들어 - char string[50]; 길이 50자의 문자열

초기화

  • 단일 문자 상수 사용 -
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
  • 문자열 상수 사용하기 -
char string[10] = "Hello":;

액세스 − '\0'이 나타날 때까지 문자열에 액세스하는 데 사용되는 제어 문자열 "%s"가 있습니다.

strstr() 함수

  • 메인 문자열에 하위 문자열이 있는지 여부를 검색하는 데 사용됩니다.

  • s1에서 s2가 처음 나타나는 포인터를 반환합니다.

구문

strstr() 함수의 구문은 다음과 같습니다 -

strstr(mainsring,substring);

예시

다음 프로그램은 strstr() 함수의 사용법을 보여줍니다.

#include<stdio.h>
void main(){
   char a[30],b[30];
   char *found;
   printf("Enter a string:\n");
   gets(a);
   printf("Enter the string to be searched for:\n");
   gets(b);
   found=strstr(a,b);
   if(found)
      printf("%s is found in %s in %d position",a,b,found-a);
   else
      printf("-1 since the string is not found");
}

출력

위의 프로그램이 실행되면 다음과 같은 결과가 생성됩니다 -

Enter a string: how are you
Enter the string to be searched for: you
you is found in 8 position

예시 2

strstr() 함수에 대한 다른 프로그램을 봅시다.

strstr 라이브러리 함수를 사용하여 문자열이 다른 문자열에 하위 문자열로 존재하는 경우 찾을 C 프로그램이 아래에 나와 있습니다.

#include<stdio.h>
#include<string.h>
void main(){
   //Declaring two strings//
   char mainstring[50],substring[50];
   char *exists;
   //Reading strings//
   printf("Enter the main string : \n ");
   gets(mainstring);
   printf("Enter the sub string you would want to check if exists in main string :");
   gets(substring);
   //Searching for sub string in main string using library function//
   exists = strstr(mainstring,substring);
   //Conditions//
   if(exists){
      printf("%s exists in %s ",substring,mainstring);
   } else {
      printf("'%s' is not present in '%s'",substring,mainstring);
   }
}

출력

위의 프로그램이 실행되면 다음과 같은 결과가 생성됩니다 -

Enter the main string : TutorialsPoint c Programming
Enter the sub string you would want to check if exists in main string :Programming
Programming exists in TutorialsPoint c Programming