Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a string variable named greeting.
C++
#include <iostream> #include <string> int main() { std::string [1] = "Hello"; std::cout << greeting << std::endl; return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name than the one printed.
Forgetting to include header.
✗ Incorrect
The variable name should be greeting to match the output line.
2fill in blank
mediumComplete the code to get the length of the string greeting.
C++
#include <iostream> #include <string> int main() { std::string greeting = "Hello"; std::cout << greeting.[1]() << std::endl; return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
len() which is not a C++ string method.Using
count() which does not exist for strings.✗ Incorrect
The correct method to get string length in C++ is length().
3fill in blank
hardFix the error in the code to concatenate two strings correctly.
C++
#include <iostream> #include <string> int main() { std::string first = "Hello, "; std::string second = "World!"; std::string combined = first [1] second; std::cout << combined << std::endl; return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
& which is for addresses or references.Using
* which is for multiplication.✗ Incorrect
In C++, strings are concatenated using the + operator.
4fill in blank
hardFill both blanks to create a substring from greeting starting at index 2 with length 3.
C++
#include <iostream> #include <string> int main() { std::string greeting = "Hello"; std::string part = greeting.substr([1], [2]); std::cout << part << std::endl; return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the start index and length.
Using incorrect indices causing wrong substring.
✗ Incorrect
The substring starts at index 2 and has length 3.
5fill in blank
hardFill all three blanks to check if the string greeting contains the character 'e' using find method.
C++
#include <iostream> #include <string> int main() { std::string greeting = "Hello"; if (greeting.[1]([2]) [3] std::string::npos) { std::cout << "Found 'e'" << std::endl; } else { std::cout << "Not found" << std::endl; } return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
== instead of != in the condition.Searching for a string instead of a character.
✗ Incorrect
The find method returns the position or std::string::npos if not found. We check if it is not equal to npos to confirm presence.