Write a program that takes two input strings S1 and S2 and finds if S2 is a substring of S1 or not. If S2 is a substring of S1, the program should print the index at S1 at which there is a match. If S2 is not a substring of S1, the program should print -1. If S2 appears in S1 multiple times, print the first index in S1 at which the match occurred.

INPUT:
Two strings S1 and S2, separated by whitespace.

OUTPUT:
One integer, which is either the index at which the match occurred or -1. Remember, the indices start at 0 for arrays.

CONSTRAINTS:
Each string contains at most 19 characters.
The strings will contain only letters from the alphabet (a-z and A-Z).
Match has to be case-sensitive.

Recommended Answers

All 6 Replies

Show the code you have ... and where you think you are stuck ...

#include <stdio.h>
#include <string.h>

int main() {
    char st1[19];
    char st2[19];
    int cnt,i,k,c,len,m,sign;
    scanf("%s %s", st1, st2);
    len=strlen(st1);
    for(i=0; i<len; i++) {
        c=0;
        if (st1[i] == st2[c]) {
            m = i;
            sign = 0;
            cnt = 0;
            while(st2[c] != '\0' && sign!=1) {
                if (st1[m] == st2[c]) {
                    m++;
                    c++;
                    cnt++;
                } else
                    sign=1;
            }
            if (sign == 0) {
                printf("%d",i);
                k=1;
            }
        }
    }
    if (k != 1)
        if (sign!=0)
            printf("-1");
    return 0;
}

all test cases are passed except last one..anybody hlp..

Input Expected Output Actual Output
coolgoose oo 1 15

try something like

string s1;
string s2;

if (s1.Contains(s2)) do something; else do something else;

also see s1.IndexOf(s2)

Sorry I posted this to the wrong question

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.