-9
string longest_common_Substring(string a, string b) {

string best = ""; 
string subString = ""; 
//vector < vector<int>> s[a.length]; 

int max = a.length() + b.length(); 


for (int i = 0; i <= a.length(); i++)
{
    for (int k = 0; k <= b.length() -i - 1; k++)
    {
        subString = a.substr(i, k);
        if (b.find(subString)== true && subString.length() > best.length())
        {
            best = subString;
        }
    }

}

return best; }

My sample input is longest_common_Substring("the rain", " in spain") and the output is "in". The correct output is "ain"

  • 8
    After almost five years as a member, it's really time to read [the help pages](http://stackoverflow.com/help), especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). Also [take the SO tour](http://stackoverflow.com/tour) and [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). And of course learn how to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve). – Some programmer dude Jun 19 '18 at 07:34
  • 3
    I also recommend that you read [this SO question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/), and all of http://idownvotedbecau.se/ to learn some reasons why you will get negative votes on your question in its current state. – Some programmer dude Jun 19 '18 at 07:35
  • 2
    Lastly, please search for "longest common substring c++". It will give you a lot of hits, including many here on Stack Overflow. – Some programmer dude Jun 19 '18 at 07:36
  • 3
    Possible duplicate of [How to find Longest Common Substring using C++](https://stackoverflow.com/questions/10248728/how-to-find-longest-common-substring-using-c) – Fantastic Mr Fox Jun 19 '18 at 07:39
  • @FantasticMrFox In this case OP needs to debug and fix their code. I don't think "just remove it and copy another implementation" is an answer. – user202729 Jul 14 '18 at 06:04

1 Answers1

0

You should change your if condition. string::find returns the position of the found string or string::npos if no string was found. string::find does not work with true and false. true is converted to 1. Therefor b.find(subString)== true is only true if subString is found at position 1 in b. You can verify this behavior with

#include <iostream>
#include <string>

int main() {
    std::string a = "Text";

    if (a.find("Text") == true) std::cout << 1 << std::endl;
    if (a.find("ext") == true) std::cout << 2 << std::endl;
    if (a.find("xt") == true) std::cout << 3 << std::endl;
    if (a.find("t") == true) std::cout << 4 << std::endl;
    return 0;
}

Output is 2

Try

b.find(subString) != b.npos

to fix your problem.

Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62