[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Searching a string array for substring

Posted on 2004-11-02
6
Medium Priority
?
283 Views
Last Modified: 2012-05-05
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
0
Comment
Question by:Sixpach71
6 Comments
 
LVL 22

Assisted Solution

by:grg99
grg99 earned 300 total points
ID: 12475872
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
 
LVL 11

Assisted Solution

by:KurtVon
KurtVon earned 300 total points
ID: 12475886
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
 
LVL 86

Assisted Solution

by:jkr
jkr earned 300 total points
ID: 12476002
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 23

Assisted Solution

by:brettmjohnson
brettmjohnson earned 300 total points
ID: 12478235
>    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
 

Author Comment

by:Sixpach71
ID: 12487758
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
 
LVL 2

Accepted Solution

by:
arun80_inin earned 300 total points
ID: 12490912
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

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
Suggested Courses

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question