69.9k views
5 votes
5.23 LAB: Contains the character

Write a program that reads an integer, a list of words, and a character. The integer signifies how many words are in the list. The output of the program is every word in the list that contains the character at least once. For coding simplicity, follow each output word by a comma, even the last one. Add a newline to the end of the last output. Assume at least one word in the list will contain the given character.

Ex: If the input is:

4 hello zoo sleep drizzle z
then the output is:

zoo,drizzle,
To achieve the above, first read the list into a vector. Keep in mind that the character 'a' is not equal to the character 'A'.

User Stefan
by
5.8k points

2 Answers

5 votes

Answer:

In C++:

#include<iostream>

#include<vector>

using namespace std;

int main() {

int len;

cout<<"Length: "; cin>>len;

string inpt;

vector<string> vect;

for(int i =0;i<len;i++){

cin>>inpt;

vect.push_back(inpt); }

char ch;

cout<<"Input char: "; cin>>ch;

for(int i =0;i<len;i++){

size_t found = vect.at(i).find(ch);

if (found != string::npos){

cout<<vect.at(i)<<" ";

i++;

}

}

return 0;

}

Explanation:

This declares the length of vector as integer

int len;

This prompts the user for length

cout<<"Length: "; cin>>len;

This declares input as string

string inpt;

This declares string vector

vector<string> vect;

The following iteration gets input into the vector

for(int i =0;i<len;i++){

cin>>inpt;

vect.push_back(inpt); }

This declares ch as character

char ch;

This prompts the user for character

cout<<"Input char: "; cin>>ch;

The following iterates through the vector

for(int i =0;i<len;i++){

This checks if vector element contains the character

size_t found = vect.at(i).find(ch);

If found:

if (found != string::npos){

Print out the vector element

cout<<vect.at(i)<<" ";

And move to the next vector element

i++;

}

}

User Kirk Liemohn
by
5.1k points
2 votes

Below is the Python code that reads an integer, a list of words, and a character, and outputs every word in the list that contains the character at least once

def contains_character(words, char):

for word in words:

if char in word.lower(): # Check for lowercase version of the character

return True

return False

n = int(input("Enter the number of words: "))

words = []

for i in range(n):

word = input("Enter word: ")

words.append(word.lower()) # Convert all words to lowercase

char = input("Enter the character: ")

if contains_character(words, char):

for word in words:

if char in word.lower(): # Output words containing the character

print(word, end=",")

print()

else:

print("None")

So, the code first asks the user for the number of words, then reads the words one by one and appends them to a list.

Then, it asks for the character to search for and calls the contains_character function to check if any of the words contain the character.

User ISTB
by
5.6k points