Embercode
✕
Character Arrays and StringsQuick quiz

Prefixes

6 questions. Covers Longest common prefix.

Questions 1 to 5 of 6

  1. 1. What does this program print? ``cpp #include <iostream> #include <string> #include <vector> std::string shorten_prefix(const std::vector<std::string>& words) { if (words.empty()) return ""; std::string prefix = words.front(); for (const std::string& w : words) { while (!w.starts_with(prefix)) { prefix.pop_back(); } } return prefix; } int main() { std::cout << "[" << shorten_prefix({"carpet", "cart", "cartoon"}) << "]\n"; } ``
  2. 2. What does this program print? ``cpp #include <cstddef> #include <iostream> #include <string> #include <vector> std::string column_scan(const std::vector<std::string>& words) { if (words.empty()) return ""; const std::string& first = words.front(); for (std::size_t col = 0; col < first.size(); ++col) { for (const std::string& w : words) { if (col >= w.size() || w[col] != first[col]) { return first.substr(0, col); } } } return first; } int main() { std::cout << "[" << column_scan({"same", "sample"}) << "]\n"; } ``
  3. 3. This function should return the longest common prefix of a list of words. What is the bug? ``cpp std::string shorten_prefix(const std::vector<std::string>& words) { std::string prefix = words.front(); for (const std::string& w : words) { while (!w.starts_with(prefix)) { prefix.pop_back(); } } return prefix; } ``
  4. 4. This function should return the longest common prefix of a list of words. What is the bug? ``cpp std::string shorten_prefix(const std::vector<std::string>& words) { if (words.empty()) return ""; std::string prefix = words.front(); for (const std::string& w : words) { while (!w.starts_with(prefix)) { prefix.erase(0, 1); // remove the first letter } } return prefix; } ``
  5. 5. The C++20 member function that checks whether a std::string begins with a given piece is named ____. Write the name only.

    Type your answer.

5 question(s) left on this page.

Typed answers ignore extra spaces and, for most questions, capital letters.