2

The code will get two string from user and checks the string , includes substring as the second input or not.

    string st1;
    string subst1;
    string message = " ";
    cout << "Enter string and subst:";
    cin >> st1;
    cin >> subst1;

    for (int a=0; a < st1.length(); a++) {
        if (st1[a] == subst1[0]) {
            for (int k = 0; k < subst1.length(); k++) {
                if (st1[a + k] == subst1[k])
                    message = "True";
                else
                    message = "False";
            }
        }
    }
    cout << message;

This code does not work inputs like "alice" and "ba". The output should be false but when I execute the code program directly ended

1
  • If your code never evaluates str1[a] == subst1[0] as true then message will not get set to false and subsequently gets left as the single white space. It would work for say, Alice and Abba. Commented Oct 31, 2015 at 22:45

2 Answers 2

1

Because in some cases a + k exceeds the length of the string st1:

if (st1[a + k] == subst1[k]) {
    message = "True";
}

before executing this statement, verify if a + k < st1.length()

but another remark: when message becomes False you must stop comparison else the variable message might be again True.

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

Comments

0

Why not use find():

string st1, subst1, message=" ";
cout<<"Enter string and subst:";
cin>>st1>>subst1;
if (st1.find(subst)==string::npos) 
    message="Not found"; 
else message ="Found"; 

If you're not allowed to use this approach, then I propose you the following:

string st1, subst1, message=" ";
bool found=false; 
cout<<"Enter string and subst:";
cin>>st1 >>subst1;

for (int a=0; !found && a<st1.length();a++) {
    if (st1[a]==subst1[0]) {
        found = true;  // there's some hope 
        for (int k=0; found && k<subst1.length(); k++) {
           if (a+k>=st1.length() || st1[a+k]!=subst1[k])  // oops! might overflow or fail
                 found = false;   // this will also end the inner loop
        }
    }
}
message = found ?  "True":"False";
cout<< message<<endl;

The principle is that for a compare to be successfull, all chars must be equal. But if a single char fails, you shall stop the failed comparison.

Here a live demo

2 Comments

I found this solution but I want to code the solution with using loops
@moreeff I supspected it, so I've edited to give also a loop approach. The trick for the compare to be successfull is that ALL chars must be equal, but the first char that is different means it failed.

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.