top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Write a C function that takes two strings and returns true if one string is the substring of other?

0 votes
537 views
Write a C function that takes two strings and returns true if one string is the substring of other?
posted Aug 23, 2016 by Mohammed Hussain

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

Basically you need a strstr function of C...

If string contains substring, the return value is the location of the first matching instance of substring in string. If string doesn't contain substring, the return value is 0. Matching is done on an exact character-for-character basis with no wildcards or special characters., if found then returns the starting position of the substring within the string.

Here is the sample implemetation -

char *
strstr(string, substring)
    register char *string;  /* String to search. */
    char *substring;        /* Substring to try to find in string. */
{
    register char *a, *b;

    /* First scan quickly through the two strings looking for a
     * single-character match.  When it's found, then compare the
     * rest of the substring.
     */

    b = substring;
    if (*b == 0) {
    return string;
    }
    for ( ; *string != 0; string += 1) {
    if (*string != *b) {
        continue;
    }
    a = string;
    while (1) {
        if (*b == 0) {
        return string;
        }
        if (*a++ != *b++) {
        break;
        }
    }
    b = substring;
    }
    return (char *) 0;
 }
answer Aug 24, 2016 by Salil Agrawal
Similar Questions
+1 vote

Given a singly linked list of integers, write a function in java that returns true if the given list is palindrome, else returns false

+2 votes

Given a set of random strings, write a function that returns a set that groups all the anagrams together.

Ex: star, dog, car, rats, arc - > {(star, rats), (arc,car), dog}

–1 vote

Write a C program to check if the given string is repeated substring or not.
ex
1: abcabcabc - yes (as abc is repeated.)
2: abcdabababababab - no

+2 votes

Assumption:
The input strings will contain only numeric digits
The input strings can be of any large lengths
The lengths of the two input string need not be the same
The input strings will represent only positive numbers
Example

If input strings are “1234” and “56”, the output string should be “1290”
If input strings are “56” and “1234”, the output string should be “1290”
If input strings are “123456732128989543219” and “987612673489652”, the output string should be “123457719741663032871”

...