3

Below is the code template and under /* write your code here */ is my own code. The template should be correct but there is sth wrong with my code.

My algorithm is to iterate through str until finding the null character. Then compare each character, if they are the same then iterate through both str and sub, otherwise set continue to iterate through str and reset to the first character of substr.

#include <stdio.h>
int findSubstring(char *str, char *substring);
int main()
{
    char str[40], substr[40];
    printf("Enter the string: ");
    gets(str);
    printf("Enter the substring: ");
    gets(substr);
    printf("findSubstring(): %d\n", findSubstring(str, substr));
    return 0;
}
int findSubstring(char *str, char *substr)
{
    /* write your code here */
    int i = 0, j = 0;
    while ((str[j] != '\0')||(substr[i] != '\0')) {
        if (substr[i] != str[j]) {
            j++;
            i = 0;
        }
        else {
            i++;
            j++;
        }
    }
    if (substr[i] == '\0')
        return 1;
    else
        return -1;
}
4
  • 2
    Do you really think that *(str + j) is more readable than str[j]? Commented Feb 25, 2016 at 15:26
  • How do you know something is wrong? What goes wrong on what input? Commented Feb 25, 2016 at 15:28
  • yesterday i have seen very similar thing again : stackoverflow.com/questions/35595389/… Commented Feb 25, 2016 at 15:29
  • 1
    Thks haha I am quite new to c programming str[j] is definitely more readable. But thats not the reason the program doesnt work :( Commented Feb 25, 2016 at 15:29

3 Answers 3

7
  • Do not use gets(), which has unavoidable risk of buffer overrun.
  • The condition of the loop is wrong. The loop should exited if one of *(str + j) or *(substr + i) is a (terminating) null character.

Fixed code:

#include <stdio.h>
int findSubstring(char *str, char *substring);
void safer_gets(char *str, size_t max);
int main(void)
{
    char str[40], substr[40];
    printf("Enter the string: ");
    safer_gets(str, sizeof(str));
    printf("Enter the substring: ");
    safer_gets(substr, sizeof(str));
    printf("findSubstring(): %d\n", findSubstring(str, substr));
    return 0;
}
int findSubstring(char *str, char *substr)
{
    int i = 0, j = 0;
    while ((*(str + j) != '\0')&&(*(substr + i) != '\0')) {
        if (*(substr + i) != *(str + j)) {
            j++;
            i = 0;
        }
        else {
            i++;
            j++;
        }
    }
    if (*(substr + i) == '\0')
        return 1;
    else
        return -1;
}
void safer_gets(char *str, size_t max)
{
    int i;
    fgets(str, max, stdin);
    for (i = 0; *(str + i) != '\0'; i++) {
        if (*(str + i) == '\n') {
            *(str + i) = '\0';
            break;
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much for the comprehensive comment :)
0

/*--------------------------One more simple example-----------------------------

Find the words from a set of words containing a given substring?

Input: Set of Words: [blackcat, blackdog, blackrat, whitetiger, blueelephant],

Substring: black

Output:[blackcat, blackdog, blackrat]

-----------------------------------------------------------------------------------------*/

#include <iostream>
#include <cstring>
int substring(char* sub,char* string);
int main()
{
    const char* Names[] { "blackcat", "blackdog", "blackrat", "whitetiger", "blueelephant" };
    char substr[]{ "black" };
    int found{ -1 };
    for (auto strings: Names)
    {
        found = substring(substr, const_cast<char*>(strings));
        if (found != -1) {
            std::cout << strings  << " ";
        }
    }
    std::cout << std::endl;
    return 0;
}

int substring(char* sub, char* string)
{
    int i{};
    int j{};
    while ((string[i] != '\0') && (sub[j] != '\0'))
    {
        if (string[i] != sub[j]) {
            j++;
            i = 0;
        }
        else {
            i++;
            j++;
        }
    }
    if (sub[j] == '\0' && i != 0) {
        return 1;
    }
    else {
        return -1;
    }
}

Comments

-1
#include<stdio.h>
#include<conio.h>
void main()
{
    char s[100],sub[50];
    int i,j,c=0;
    clrscr();
    printf("enter string and substring\n");
    gets(s);
    printf("\n");
    gets(sub);
    printf("\n");
    i=0;
    j=0;
    while(s[i]!='\0')
    {
        if(s[i]!=sub[j])
            i++;
        else if(s[i]==sub[j])
        {
            while(sub[j]!='\0')
            {
                if(s[i]==sub[j])
                {
                    i++;
                    j++;
                    c++;
                }
                else
                {
                    c=0;
                    break;
                }
            }
        }
    }
     if(c!=0)
     printf("\nsubstring  is present \n ");
     else
     printf("\nsubstring  is absent \n ");
    getch();
}

1 Comment

Adding a brief explanation of your answer would be nice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.