Write a function to check whether string s1 is a substring of string s2. The function returns the first index in s2 if there is a match. Otherwise, return -1. For example, the function should return 2 if s1 is "to" and s2 is "October". If s1 is "andy" and s2 is "candy", then the function should return 1. The function prototype is as follows:
int indexOf(const char *s1, const char *s2)
Write a program to test the function.
#include <stdio.h> int indexOf(const char *s1, const char *s2); int main() { printf("%d\n", indexOf("to", "October")); printf("%d\n", indexOf("andy", "candy")); printf("%d\n", indexOf("hi", "hello")); return 0; } int indexOf(const char *s1, const char *s2) { int i = 0, j; while (s2[i]) { j = 0; while (s1[j]) { if (s1[j] != s2[i+j]) break; j++; } if (s1[j] == 0) return i; i++; } return -1; }
Get Answers For Free
Most questions answered within 1 hours.