std::string_view
Completed
Write bool startsWith(string_view s, string_view prefix) and endsWith without copying strings. Read a prefix, a suffix and n words; print the words that start with the prefix and end with the suffix.
Input
Line 1: prefix suffix. Then n and n words.
Output
Matching words on one line, or none.
Example
Input
pre ing 5 prefixing preparing pressing playing prepare
Output
prefixing preparing pressing
Editor
C++
Hints
string_view is a cheap, read-only window onto existing text.
Solution explanation
Taking string_view parameters avoids copies for any string-like argument.
Show solution
#include <iostream>
#include <string>
#include <string_view>
using namespace std;
bool startsWith(string_view s, string_view prefix) {
return s.size() >= prefix.size() && s.substr(0, prefix.size()) == prefix;
}
bool endsWith(string_view s, string_view suffix) {
return s.size() >= suffix.size() && s.substr(s.size() - suffix.size()) == suffix;
}
int main() {
string prefix, suffix;
int n;
cin >> prefix >> suffix >> n;
bool any = false;
for (int i = 0; i < n; i++) {
string w;
cin >> w;
if (startsWith(w, prefix) && endsWith(w, suffix)) {
cout << (any ? " " : "") << w;
any = true;
}
}
cout << (any ? "\n" : "none\n");
return 0;
}