its supposed to search string a for string b and once string a matches the requirments it should be printed alongside string b. anyway it does that but the output isnt
c c
c c
c c
what it should be but it shows double that for whatever reasons:

#include <iostream>
using namespace std;

int main()
   string source= "a bb ccc dddd",
   for (int i=0; i< source.length(); i++)
       if ((source[i] == search[0]) || (source[i+search.length()] == search[search.length()] ) )
                      for (int j=i,k=0; j<(i+search.length()); j++,k++)
                          if (source[j] == search[k]) { cout<< source[j] << " " << search[k] <<endl; }
    return 0;

Recommended Answers

All 5 Replies

Think before drink. Take a pencil and a sheet of paper, verify your search algorithm(es).
Yes, I know the answer but it's your assignment, not mine...

beyond the "i think" the error should be in the inner for cycle i cant come up with anything solid

i solved the problem adding break on the last if statement, however im not very clear on why should it be there as all it does is skips the whole statement which shouldnt matter as the said statement should only get executed only if it meets the requirments. could anyone give some explanation? :|

Well, test your problem "solution" on strings which do not match one another. Outer loop runs from i = 0 to source.length()-1, right? So the inner loop runs from j = source.length()-1 to source.length()-1+search.length()-1 > source.length()! The program "searches" after source string body...
Stop to bail out a boat, better stop a leak.
What's the last position of the search string in our process?

Source SSSSSSSSSS source.length() - lenS
searCh      CCCCC search.length() - lenC
pos    0    x

What's the outer loop max counter? Obviously, it's equal to lenS - lenC.
What's the inner loop max counter? Obviously, it's equal to lenC.
When the searched string is found? Obviously, when inner loop ended normally.
When we need to try the next position? Obviously, when inner loop is broken.
What happens if all loops ended normally? Obviously, our search failed: no such substring in the source string...
Try to implement this algorithm now.

How do you want to print it like? Your input string is "A BB CCC DDDD" & search string is "CCC" so how it should be printed ?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.