Challenge - 5 Problems
String Functions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of string find function
What is the output of this C++ code snippet?
C++
#include <iostream> #include <string> int main() { std::string s = "hello world"; std::cout << s.find("world") << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Remember that string::find returns the index of the first character of the found substring or std::string::npos if not found.
✗ Incorrect
The substring "world" starts at index 6 in "hello world". So s.find("world") returns 6.
❓ Predict Output
intermediate2:00remaining
Result of string substr function
What does this C++ code print?
C++
#include <iostream> #include <string> int main() { std::string s = "programming"; std::cout << s.substr(3, 4) << std::endl; return 0; }
Attempts:
2 left
💡 Hint
substr(pos, len) returns a substring starting at pos with length len.
✗ Incorrect
Starting at index 3 (0-based), the substring of length 4 is "gram".
❓ Predict Output
advanced2:00remaining
Output of string compare function
What is the output of this C++ program?
C++
#include <iostream> #include <string> int main() { std::string a = "apple"; std::string b = "apricot"; std::cout << a.compare(b) << std::endl; return 0; }
Attempts:
2 left
💡 Hint
string::compare returns 0 if equal, positive if first string is lexicographically greater, negative if smaller.
✗ Incorrect
"apple" is lexicographically smaller than "apricot", so compare returns a negative number.
❓ Predict Output
advanced2:00remaining
Effect of string erase function
What is the output of this C++ code?
C++
#include <iostream> #include <string> int main() { std::string s = "abcdef"; s.erase(2, 3); std::cout << s << std::endl; return 0; }
Attempts:
2 left
💡 Hint
erase(pos, len) removes len characters starting at pos.
✗ Incorrect
Removing 3 characters starting at index 2 removes 'c', 'd', 'e', leaving "abf".
🧠 Conceptual
expert2:00remaining
Behavior of string::npos in find function
What is the value and meaning of std::string::npos in C++ string functions?
Attempts:
2 left
💡 Hint
Check the documentation for string::npos and its role in find functions.
✗ Incorrect
std::string::npos is a static constant representing the largest possible size_t value. It signals that a substring was not found.