0

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?

7
  • Function findString does not return a pointer suitable for printf's %s format, and the code only finds the substring if it starts at the beginning. It was luck, or bad luck. My attempt crashed whether or not there is a space in the string. You are probably overflowing the child argument anyway. Commented Feb 12, 2019 at 21:49
  • findString() returns an index, not a string. You should print the result with %d, not %s. Commented Feb 12, 2019 at 21:53
  • findString() doesn't match a substring. It checks whether corresponding characters in the two strings are identical, and counts them. E.g. abcdef and xbc1e3 will count 3 matches for b, c, and e. Also, it will access outside the child if it's shorter than the mother. Commented Feb 12, 2019 at 21:57
  • Hi guys, If I remove printf and call the function like that: findString ("a chatterbox", "hat"); I get the same result. Commented Feb 12, 2019 at 22:03
  • @Barmar - you mean that this counts not the "hat" string only h a and t? So the logic is wrong? Commented Feb 12, 2019 at 22:07

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

1 Comment

So basically you are saying that I should go with separate for loops and make a comparison later. Thanks!
0

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.

1 Comment

Thank you very much! This is a great explanation!

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.