Challenge - 5 Problems
String Handling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of string concatenation and length
What is the output of this C++ code snippet?
C++
#include <iostream> #include <string> int main() { std::string a = "Hello"; std::string b = "World"; std::string c = a + " " + b; std::cout << c << " " << c.length() << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Remember that adding a space between strings adds one character to the length.
✗ Incorrect
The strings "Hello" and "World" are concatenated with a space in between, so the result is "Hello World" which has 11 characters including the space.
❓ Predict Output
intermediate2:00remaining
Output of string find method
What will this program print?
C++
#include <iostream> #include <string> int main() { std::string s = "programming"; size_t pos = s.find("gram"); std::cout << pos << std::endl; return 0; }
Attempts:
2 left
💡 Hint
The find method returns the index where the substring starts.
✗ Incorrect
The substring "gram" starts at index 3 in "programming" (p=0, r=1, o=2, g=3).
❓ Predict Output
advanced2:00remaining
Output of string substr and concatenation
What is the output of this code?
C++
#include <iostream> #include <string> int main() { std::string s = "abcdef"; std::string t = s.substr(1, 3) + s.substr(4); std::cout << t << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Check carefully the substr parameters and concatenation.
✗ Incorrect
s.substr(1,3) is "bcd" and s.substr(4) is "ef", concatenated gives "bcdef".
❓ Predict Output
advanced2:00remaining
Output of string comparison
What does this program print?
C++
#include <iostream> #include <string> int main() { std::string a = "apple"; std::string b = "banana"; if (a < b) { std::cout << "a < b" << std::endl; } else { std::cout << "a >= b" << std::endl; } return 0; }
Attempts:
2 left
💡 Hint
Strings are compared lexicographically (dictionary order).
✗ Incorrect
"apple" is lexicographically less than "banana", so the output is "a < b".
❓ Predict Output
expert2:00remaining
Output of string erase and insert
What is the output of this program?
C++
#include <iostream> #include <string> int main() { std::string s = "hello world"; s.erase(5, 1); s.insert(5, ","); std::cout << s << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Erase removes the space, insert adds a comma at the same position.
✗ Incorrect
The space at index 5 is erased, then a comma is inserted at index 5, resulting in "hello,world".