16. Дано рядок. Вказати ті слова, які містять принаймні одну літеру "к"
Написати Код на Python та C++
Ответы
Python
def find_words_with_letter_k(string):
words = string.split()
result = []
for word in words:
if "k" in word:
result.append(word)
return result
print(find_words_with_letter_k("Given a string. Indicate those words that contain at least one letter 'k'"))
C++
#include <iostream>
#include <vector>
#include <string>
std::vector<std::string> find_words_with_letter_k(const std::string& str) {
std::vector<std::string> words;
std::string word;
for (const char& c : str) {
if (c == ' ') {
words.push_back(word);
word.clear();
} else {
word += c;
}
}
words.push_back(word);
std::vector<std::string> result;
for (const std::string& word : words) {
for (const char& c : word) {
if (c == 'k') {
result.push_back(word);
break;
}
}
}
return result;
}
int main() {
const std::string str = "Given a string. Indicate those words that contain at least one letter 'k'";
const auto result = find_words_with_letter_k(str);
for (const std::string& word : result) {
std::cout << word << ' ';
}
std::cout << '\n';
return 0;
}