Find if a given sequence of characters are present in a parent string in C++

In this tutorial, we are going to learn to check whether a given string is a part of a given parent string or not in C++. For example, if the given parent string is “codespeedy”. We should check whether “code” is a part of this string or not. We can do this by find function in-built in C++. The function takes the string that we search as a parameter. It returns the position of the first occurrence of the first character in the parent string.

In the above example, the function will return 0. Since code is present in codespeedy. The first occurrence of the first character(c) in parent string is at position 0.

usage:

parent string.find(string to be found).

code to find whether a given string is a part of the parent string:

#include<iostream>
using namespace std;
int main(){
    string s1,s2;
    cout<<"Enter the parent string"<<endl;
    getline(cin,s1);
    cout<<"Enter the string to be found"<<endl;
    getline(cin,s2);
    int found =s1.find(s2);
    cout<<"The string's first occurrence found at position"<<endl;
    cout<<found<<endl;

}

Output:

Enter the parent string
codespeedy
Enter the string to be found
code
The string's first occurrence found at position
0

code to find whether a given character is a part of parent string:

#include<iostream>
using namespace std;
int main(){
    string s1;
    char c;
    cout<<"Enter the parent string"<<endl;
    getline(cin,s1);
    cout<<"Enter the charcter to be found"<<endl;
    cin>>c;
    int found =s1.find(c);
    cout<<"The character's first occurrence found at position"<<endl;
    cout<<found<<endl;

}

Output:

Enter the parent string
codespeedy
Enter the character to be found
e
The character's first occurrence found at position
3

 

Leave a Reply

Your email address will not be published. Required fields are marked *