This code has to be written in c Write a series of assignmen
This code has to be written in c++. 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. There does not need to be any user input. You can use the string \"John and I went to the park, and then to the store. We will soon return with milk and eggs.\" have a code find the numerical position of the three \"and\"s in the string. The numerical position can be where the \'a\' is in the word \"and\"
Solution
PROGRAM CODE:
#include <iostream>
#include <string>
using namespace std;
int main() {
//variables to store the indexes - Index starts at position 0
int first = -1, second = -1, third = -1, index = 0;
//string statement
string statement = \"John and I went to the park, and then to the store. We will soon return with milk and eggs\";
//using while loop to loop through each character in the string
while(index+2 < statement.length())
{
if(statement[index] == \'a\' && statement[index+1] ==\'n\' && statement[index+2] == \'d\')
{
if(first < 0)
first = index;
else if(second< 0)
second = index;
else if(third < 0)
{
third = index;
break;
}
}
index++;
}
cout<<\"Index 1: \"<<first<<\"\ Index 2: \"<<second<<\"\ Index 3: \"<<third;
return 0;
}
OUTPUT:
