0
0
C++programming~20 mins

String handling basics in C++ - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
String Handling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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;
}
AHello World 10
BHelloWorld 10
CHello World 11
DHelloWorld 11
Attempts:
2 left
💡 Hint
Remember that adding a space between strings adds one character to the length.
Predict Output
intermediate
2: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;
}
A3
B0
C-1
D7
Attempts:
2 left
💡 Hint
The find method returns the index where the substring starts.
Predict Output
advanced
2: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;
}
Abcdef
Bfedcb
Ccdef
Dbcde
Attempts:
2 left
💡 Hint
Check carefully the substr parameters and concatenation.
Predict Output
advanced
2: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;
}
ARuntime error
Ba >= b
CCompilation error
Da < b
Attempts:
2 left
💡 Hint
Strings are compared lexicographically (dictionary order).
Predict Output
expert
2: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;
}
Ahello world
Bhello,world
Chello, world
Dhelloworld
Attempts:
2 left
💡 Hint
Erase removes the space, insert adds a comma at the same position.