Answer to Question #46779 in C++ for hassan

Question #46779
Write a function that takes two arguments both strings (character pointers). The program checks to see whether or not the second string is a substring of the first. The function returns true if 2nd string is sub-string of first string otherwise it must return false. You are not allowed to use strtok library function.
Expert's answer
#include <stdlib.h>
#include <iostream> // for cout and cin
#include <stdio.h>
#include <cstdlib> // for system
#define lim 256
using namespace std;
char s1[lim];
char s2[lim];
char c;
int strlen(char s[]);
bool SubStringOrNot(char s_1[], char s_2[]);
int main()
{
int index=0;
cout<<"Enter the string "<<endl;
for ( index=0; index<lim && (c = getchar())!= EOF && c!='\n';++index)
s1[index]=c;
s1[index]='\0';
cout<<endl;
cout<<"Enter the sub string"<<endl;
index = 0;
for ( index=0; index<lim && (c = getchar())!= EOF && c!='\n';++index)
s2[index]=c;
s2[index]='\0';

if (strlen(&s2[0]) > strlen(&s1[0])) cout<<&s2[0]<<" is a substring"<<endl;
else
{
if (SubStringOrNot(s1, s2)) cout<<&s2[0]<<" is a substring"<<endl;
else
cout<<&s2[0]<<" is not a substring"<<endl;
}
system("pause");
return 0;
}
int strlen(char s[])
{
int i = 0;
while (s[i] != '\0')
++i;
return i;
}
bool SubStringOrNot(char s_1[], char s_2[])
{
int index = 0;
int howManyWordConcided = 0;
bool subOrNot = false;;
for (int i = 0; i < strlen(s_1); i++)
{
if (s_1[i] == s_2[0])
{
for (int j = 0; j < strlen(s_2); j++)
{
if (s_1[i+j] == s_2[j]) ++howManyWordConcided;
}
}
if (howManyWordConcided == strlen(s_2))
{
subOrNot = true;
break;
}
else
howManyWordConcided = 0;

}

return subOrNot;
}


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS
paypal