'How do I output the correct value of different strings on different lines?

Given a string on one line and a second string on the second line, output the index where the second string starts in the first string.

Ex: If the input is:

Fuzzy bear
zy

the output is:

3

Note: Using a pre-defined string function, the solution can be just one line of code Butt does not have to be.

#include <iostream>
#include <string>

using namespace std;

int main() {
  string workString;
  string string2;
  int pos;

  getline(cin, workString);

  cin >> string2;

  /* Your code goes here */

  cout << pos << endl;

  return 0;
}
c++


Solution 1:[1]

cout << workString.find(String2) << endl;

Solution 2:[2]

we search for the first character of string2 if we found the match in workString then we look for other characters of string2 if we found all characters of string2 in workString in the same order then we assign the pos to j index and then we break the loop.

int i = 0;
for (int j = 0; j < workString.size(); ++j) {
    int n = 1;
     if (string2[i] == workString[j]) {
        while(n < workString.size()) {
            if(string2[i+n] == workString[j+n]){
                if ((i+n) == string2.size()) {
                  pos = j;
                  break;
                }
            }
            n++;
        }
     }
}
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jmoerdyk
Solution 2