In: Computer Science
This is a c++ code. Write a series of assignment statements (complete executable code) that find the first three positions of the string “and” in a string variable sentence. The positions should be stored in int variables called first, second and third. You may declare additional variables if necessary. The contents of sentence should remain unchanged. The sentence can be completely random.
Im having a large problem with this. It's a simple c++ code, but im unable to get it. Thank you.
#include<iostream>
#include<string>
#include<cstdlib>
#include<ctime>
using namespace std;
static const char alpha[]="abc def ghi jkl mno pqr stu vwx
yz";
int len=sizeof(alpha)-1;
char genRandom() // Random string generator function.
{
return alpha[rand()%len]; //selecting single
char
}
int main()
{
string str;
int p[3],j=0,first,second,third;
srand(time(0));
for(int z=0; z < 50; z++)
{
str=str+genRandom();
//adding of random char for forming string
}
cout<<"Randomly generated Sentence is: ";
cout <<str<<endl<<endl;
int n=str.length(); //length of Randomly generated Sentence
p[0]=p[1]=p[2]=0;
for(int i=0;i<n-2;i++) //checking for and in
Randomly generated Sentence
{
if(str[i]=='a')
{
if(str[i+1]=='n')
{
if(str[i+2]=='d')
{
p[j]=i+1; //storing of
position of and after finding
j++;
i=i+3;
}
}
}
}
first=p[0];
second=p[1];
third=p[2];
//printing of positions
cout<<"First position of and is:
"<<first<<endl;
cout<<"Second position of and is:
"<<second<<endl;
cout<<"Third position of and is:
"<<third<<endl;
}
output:-
1)
Randomly generated Sentence is: d lvk vvxzkakwvgbhhe
fbmpurpjxqppvbmb u v wg ceai
First position of and is: 0
Second position of and is: 0
Third position of and is: 0
Process exited normally.
Press any key to continue . . .
2)
Randomly generated Sentence is: klo smj adgmdgpujtkjes
v wy w eyx kbwfumt ekrw
First position of and is: 0
Second position of and is: 0
Third position of and is: 0
Process exited normally.
Press any key to continue . . .
3)
Randomly generated Sentence is: hub upn ov
ixppldiemll wyy qv o gtezf k n bk
First position of and is: 0
Second position of and is: 0
Third position of and is: 0
Process exited normally.
Press any key to continue . . .