Question 3: Write a C++ program to find a substring within a string. If found display substring found, otherwise Not Found.
Question 3: Write a C++ program to find a substring within a string. If found display substring found, otherwise Not Found.
/*
Name: Mudassar Ali
Roll: BCSF15M045 [Morning]
Assignment: No# 05
Teacher: Miss Sadia Shahzad
*/
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
cout<<"\tThis Programme will check the sub string it is or not!!\n\n";
char str [50]; // Storing the input String.
char sub_str [50]; // Storing the input Sub_String.
int i,x;
int counter = 0; // Variables declare for the loop.
cout<<"Enter the string:";
cin.getline(str,50); // Inputting the String .
cout<<"\nEnter the sub string:";
cin>> sub_str; // Inputting the Sub_String.
int len = strlen(sub_str); // To calculate the length of sub_string.
for( x = 0,i=0;str[x]!='\0'&&sub_str[i]!='\0';x++ ) // Combined condition Loop.
{
if(str[x]==sub_str[i]) // If the string and sub_string match then i will incremented by 1 and vice versa
{
i++;
if(i==len)
{
counter++;
}
}
if(str[x+1]==sub_str[i]) // if string has two same characters repeatedly. like ee, ii,
i++;
else
{
i=0;
}
}
if (i==len)
{
// If the length of sub_string equal to i then ....
cout<<"\nIt is a sub string!!\n";
cout<<"\n Found: "<<counter<<endl;
}
else
cout<<"\nIt is Not a sub string";
return 0;
}
/*
Name: Mudassar Ali
Roll: BCSF15M045 [Morning]
Assignment: No# 05
Teacher: Miss Sadia Shahzad
*/
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
cout<<"\tThis Programme will check the sub string it is or not!!\n\n";
char str [50]; // Storing the input String.
char sub_str [50]; // Storing the input Sub_String.
int i,x;
int counter = 0; // Variables declare for the loop.
cout<<"Enter the string:";
cin.getline(str,50); // Inputting the String .
cout<<"\nEnter the sub string:";
cin>> sub_str; // Inputting the Sub_String.
int len = strlen(sub_str); // To calculate the length of sub_string.
for( x = 0,i=0;str[x]!='\0'&&sub_str[i]!='\0';x++ ) // Combined condition Loop.
{
if(str[x]==sub_str[i]) // If the string and sub_string match then i will incremented by 1 and vice versa
{
i++;
if(i==len)
{
counter++;
}
}
if(str[x+1]==sub_str[i]) // if string has two same characters repeatedly. like ee, ii,
i++;
else
{
i=0;
}
}
if (i==len)
{
// If the length of sub_string equal to i then ....
cout<<"\nIt is a sub string!!\n";
cout<<"\n Found: "<<counter<<endl;
}
else
cout<<"\nIt is Not a sub string";
return 0;
}
No comments: