Find string in another string in C++

 Find string in another string in C++

Given two strings S and T, write a function to find if T is present as a substring inside S or not. If yes, return the starting index otherwise return -1.

Input format :

Line 1 : String S

Line 2 : String T

Sample Input 1:
WelcomeBack
come 
Sample Output 1:
3
Sample Input 2:
WelcomeBack
code
Sample Output 2:
-1
C++ Code:
// S and T - input strings
// You need to check if string T is present in S or not

int findString(char S[], char T[]) {
    // Write your code here
  int temp;
 for(int i=0;S[i]!='\0';i++)
    {
        int j=0;
        if(S[i]==T[j])
        {
             temp=i;
            while(S[i]==T[j])
            {
                i++;
                j++;
            }
 
            if(T[j]=='\0')
            {
                return temp;
                
            }
            else
            {
                i=temp;
                temp=0;
            }
        }
    }
 
    if(temp==0)
        return-1;
}

SHARE

Milan Tomic

Hi. I’m Designer of Blog Magic. I’m CEO/Founder of ThemeXpose. I’m Creative Art Director, Web Designer, UI/UX Designer, Interaction Designer, Industrial Designer, Web Developer, Business Enthusiast, StartUp Enthusiast, Speaker, Writer and Photographer. Inspired to make things looks better.

  • Image
  • Image
  • Image
  • Image
  • Image
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment