#include <stdio.h> int main(void) { int i; char line1[80], line2[80]; void readL
ID: 3740235 • Letter: #
Question
#include <stdio.h>
int main(void)
{
int i;
char line1[80], line2[80];
void readLine(char
buffer[]);
printf("Type in string to be searched (up to 80 characters):");
for (i = 0; i < 3; ++i)
{
readLine(line1);
}
printf("Type in string to be found (up to 80 characters):");
for (i = 0; i < 3; ++i)
{
readLine(line2);
}
return 0;
}
void readLine(char buffer[])
{
char character;
int i = 0;
do
{
character = getchar();
buffer[i] = character;
++i;
} while (character != ' ');
buffer[i - 1] = '';
}
This is my code so far, I now want to have the string in line2 be searched in the string in line1 and then make a new string containing all the words from line2 that were found in line 1. for example if line 1 was hello world my name is c and line2 was my name is, then the new string would contain my name is
Explanation / Answer
//headers
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
//main function
int main(){
string s1, s2, s3, s4;
cout << "Enter line 1 : "; getline(cin, s1);
cout << "Enter line 2 : "; getline(cin, s2);
//search words in line 2
stringstream words(s2); //extracting words
string word, output = "";
while(words >> word){ //checking the word is in s1(line1) or not
if(s1.find(word) != string::npos) { //find() is used to search the given word
output += word + " "; //appending the matched words
}
}
cout << output << endl; //displaying the matched words
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.