Challenge - 5 Problems
String Mastery in C++
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of String Concatenation in C++
What is the output of the following C++ code snippet?
DSA C++
#include <iostream> #include <string> int main() { std::string a = "Hello"; std::string b = "World"; std::string c = a + b; std::cout << c << std::endl; return 0; }
Attempts:
2 left
💡 Hint
In C++, the + operator concatenates strings without adding spaces.
✗ Incorrect
The + operator joins the two strings exactly as they are, so no space is added automatically.
❓ Predict Output
intermediateString Immutability in C++ vs Python
What will be the output of this C++ code snippet?
DSA C++
#include <iostream> #include <string> int main() { std::string s = "abc"; s[0] = 'z'; std::cout << s << std::endl; return 0; }
Attempts:
2 left
💡 Hint
In C++, std::string characters can be changed by index.
✗ Incorrect
Unlike Python strings, C++ std::string is mutable and allows character modification by index.
❓ Predict Output
advancedNull Character in C++ String
What will be printed by this C++ code?
DSA C++
#include <iostream> #include <string> int main() { std::string s = "abc\0def"; std::cout << s << std::endl; std::cout << s.size() << std::endl; return 0; }
Attempts:
2 left
💡 Hint
std::string can contain null characters inside and counts them in size.
✗ Incorrect
std::string stores all characters including nulls; size counts all characters. Printing outputs all characters until the end.
🧠 Conceptual
advancedDifference Between C-style Strings and std::string
Which statement correctly describes a key difference between C-style strings and std::string in C++?
Attempts:
2 left
💡 Hint
Think about how each stores and manages string length.
✗ Incorrect
C-style strings rely on a null terminator to mark the end; std::string stores size separately and can hold any characters including nulls.
🔧 Debug
expertWhy Does This C++ String Code Crash?
Consider this C++ code snippet. Why does it cause a runtime error?
DSA C++
#include <iostream> #include <string> int main() { const char* cstr = "hello"; std::string s(cstr); s[10] = 'x'; std::cout << s << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Check the size of the string before accessing index 10.
✗ Incorrect
The string "hello" has length 5; accessing index 10 is out of range and causes undefined behavior.
