Searching a string array for substring

I'm taking a class in C++ and I need some help with an assignment.  I need to write a program that will search a given string array for a substring provided by the user.  The only string function the instructor is allowing the class to use is strlen.  The program is also supposed to display the substring and the number of times it was found. This is what I have so far:

int main()
{
      //declare variables

      char sourceString[]="big lazy dog";
      int srcLength=(int)strlen(sourceString);
      char searchString[6];
      int searchLength=(int)strlen(searchString);
      int foundStringCounter=0;
      int index=0;

      //prompt for search string

      cout << "enter search string" << endl;

      //read input

      cin >> searchString >> endl;

      //find searchString and count
      
      while (index < srcLength)
      {
            if (searchString[index]==sourceString[index])
                  foundStringCounter = foundStringCounter + 1;
                  index = index + 1
            else
                  index = index + 1
      }
            
      //show results
      
      cout << "Source String:  " << endl << sourceString << endl;
      cout << "Search String:  " << endl << searchString << endl;
      cout << "Found:  "  << endl << foundStringCounter << " times" << endl;

      return();
}

I appreciate any help.  

Thanks,

H
Sixpach71Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

grg99Commented:
Youre kinda close, you're going to find strings that match starting at column 1 of the source string.

You need to add another loop, where if they don't match at column 1, try again at the next column,
until the match becomes impossible (startiing column + length(search) > length(source).


You might also want to speed up your search loop above, no need to continue if a match isnt found.

0
KurtVonCommented:
Your main problem here is that you are really just counting the number of identical characters in the two strings.

Obviously you need a different index into the search string than the find string, and you need to compare the character offsets for the two different indicies.  There are a number of ways to do this, and your instructor probably hinted in class what way is going to get the most points, but the simplest is just to loop through teh substring for every possible start position in the find string.

Sorry for being vague, but this is a homework assignment.

Hope this helps.
0
jkrCommented:
You could roll your own function to find a string in a string, e.g.

char* my_strstr (
        const char * strToSearch,
        const char * strToFind
        )
{
        char *iter = (char *) strToSearch;
        char *s1, *s2;

        while (*cp) // go through 'strToSearch' until NULL is found
        {
                s1 = iter;
                s2 = (char *) strToFind;

                while ( *s1 && *s2 && (*s1==*s2) )      // consecutively check
                        s1++, s2++;                              // whether 'strToFind'
                                                                              // can be found

                if (!*s2) // got it!
                        return(iter);

                iter++;
        }

        return(NULL);
}
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

brettmjohnsonCommented:
>    char searchString[6];
>    int searchLength=(int)strlen(searchString);

You attempt to determine the length of the search string before you have read
it from the user.  At the point that you call strlen(searchString), searchString
is uninitialized - it contains whatever garbage happens to be in that location of
the stack.   If that garbage happens to contain a 0 byte, you get lucky.  If not,
you risk a segmentation violation.  You could just scratch the call, since you don't
ever use the returned length.

0
Sixpach71Author Commented:
grg99,

I'm I getting closer?  I really don't mean to be so whimpy but I'm having a major mental block.  I've tried researching it on the Internet but the stuff I've found only confuses me more.  I comprehend what I've got to do, I just can't translate it to code.    

int main()
{
     //declare variables

     char sourceString[]="big lazy dog";
     int srcLength=(int)strlen(sourceString);

     char searchString[6];
     int searchLength=(int)strlen(searchString);

     int foundStringCounter=0;
     

     //prompt for search string

     cout << "enter search string" << endl;

     //read input

     cin >> searchString >> endl;

     //find searchString and count
     
     while (searchLength < srcLength)
     {
          if (sourceString[srcLength]==searchString[searchLength)
          {    foundStringCounter = foundStringCounter + 1;
               searchLength = searchLength + 1;
        {
          else
               searchLenth = searchLength + 1;
     }
         
     //show results
     
     cout << "Source String:  " << endl << sourceString << endl;
     cout << "Search String:  " << endl << searchString << endl;
     cout << "Found:  "  << endl << foundStringCounter << " times" << endl;

     return();
}



0
arun80_ininCommented:
Try this code:

main()
{
chat str[ ],substr[ ];
cout<<"enter the strnig::;"
cin>>str;
cout<<"enter the substring:";
cin>>substr;
if(strlen(substr)>strlen(str))
{
  cout<<"length of substring is greater than string";
  return();
}

int i=0,n=0;
while(i<strlen(str))
{
  j=i;
  chat match='y';
  for(k=o;((k<strlen(substr))&&(j<strlen(str));k++,j++)
  {
      if (str[k]!=substr[j])
       {
             match='n';
             break;
        }
   }
  if match='y'
  {
      n++;
      i=j;
   }
  else
     i++;
}
cout<<"number of time substr occured="<<n;
return();
}

if doesn't work change i=j as i=j+1;



try and give the comments





}
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.