Przemek Tęczar
Przemek Tęczar

Reputation: 49

Substring search in string function gives improper values

I've created a program that behaves in a strange way -- I am not sure why it is giving improper values. For example when I use input: ("a chatterbox", "hat"), it works properly:

    The starting position is 3.
String 'hat' occured for 1 time(s).

But if I remove the space ("achatterbox", "hat") it shows:

String 'hat' occured for 0 time(s).

Exercise explanation:

/* Write a function called findString() to determine if one character string exists inside another string. The first argument to the function should be the character string that is to be searched and the second argument is the string you are interested in finding. If the function finds the specified string, have it return the location in the source string where the string was found. If the function does not find the string, have it return −1. So, for example, the call Click here to view code image index = findString ("a chatterbox", "hat"); searches the string "a chatterbox" for the string "hat". Because "hat" does exist inside the source string, the function returns 3 to indicate the starting position inside the source string where "hat" was found. */

My code:

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

int findString (char motherArgument[], char childArgument[]);


int main(int argc, char const *argv[])
{

    printf("%s",findString ("a chatterbox", "hat")); //why if I remove space ' ' this does not work, why?
     return 0;
}


int findString (char motherArgument[], char childArgument[]) // is child inside the mother? 
{

    int i, flag = false, freq = 0;

    for (i = 0; i < strlen(motherArgument); i++) // going through mother
  {
    if(motherArgument[i] == childArgument[i]) //  chars equal?
    {
        flag = true;
        printf("The starting position is %d.", i - 1); // i -1 to get 3 as in the example
        freq++; // frequency
    }

  }
    if (flag = true) 
      {
         printf("\nString '%s' occured for %d time(s).\n", childArgument, freq);    
      }

        else
            {
                printf("None\n"); // false = none
                return -1;
            }


}

What am I doing wrong? Should I input the data in a different way?

Upvotes: 0

Views: 402

Answers (2)

cdlane
cdlane

Reputation: 41872

I see two problems with your code, your findString() function and your main() function. Programming to the test, let's get your main() function sorted out first. It assumes that findString() returns a string, but it doesn't--it returns an int. So we need something like:

int main(int argc, char const *argv[])
{
    char *string = "a chatterbox";

    int index = findString(string, "hat");

    if (index != -1)
    {
        printf("%s\n", string + index);
    }

    return 0;
}

Now turning to your findString() function, as @FredK and @Barmar rightly note, this is not correct:

if(motherArgument[i] == childArgument[i])

But looking beyond that, what's this all about:

freq++; // frequency

Nothing in your problem specification mentions a frequency count. Then there's that flag variable for which you include <stdbool.h> and declare it int anyway. It seems to control some printing that's not in the specification. Finally you return -1 on failure but don't explicitly return anything on success!

Let's attempt a minimal, and slightly broken, implementation of findString():

int findString(const char *string, const char *substring)
{
    for (int i = 0; i < strlen(string); i++)
    {
        if (strncmp(string + i, substring, strlen(substring)) == 0)
        {
            return i;
        }
    }

    return -1;
}

Odds are you'll now tell us you're not allowed to use strncmp(). Regardless, you now have a basic model of how these routines should interact and can fill out the code as needed. Along with the usual debugging and testing, questions to ask yourself as you program this:

What if one or both of the argument strings are an empty string? Or the same string? What happens if the substring is longer than the string? Are our loop limits correct or can we do better?

First decide what should happen in any of these cases and then make sure your code does the right thing.

Upvotes: 0

FredK
FredK

Reputation: 4084

if(motherArgument[i] == childArgument[i])

This is not correct. You should be not be using the same index for both strings.

Search the motherArgument until you find a character that matches the FIRST character of the childArgument. If found, continue checking whether subsequent characters of the two strings are equal.

Upvotes: 1

Related Questions