Checking for a string in another string

I am wondering what I need to do next for my code to check if there is a string in another string. My code below right now checks to see if the the first letter of string one is in string two. I need help coding how to check if an entire string (the whole word) is in another string, or in other words if the first string is a subscript of the second string. I think I have to add code to line 23, but I am not 100% sure. Here is my code so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <cmath>
#include <ctime>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;


  int indexOf(string s1, string s2)
{
	if (s1 > s2)
	{
		return -1;
	}
	else
	{
		char firstchar = s1.at(0);
		for (int i = 0; s1.length() - s2.length(); i++)
		{
			if (firstchar == s2.at(i))
			{
				return i;
			}
		}
	}
}

int main()
{
	string s2 = " ";
	string s1 = " ";
	cout << "Enter string 1 and 2" << endl; 
	cin >> s1 >> s2;
	cout << indexOf(s1, s2) << endl;

	return 0;
}
Last edited on
Just use string::find()
Like this:
1
2
3
string s1 = "apple";
string s2 = "app"
if (s1.find(s2) != std::string::npos) //Found it! 
Topic archived. No new replies allowed.