Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to get the length of the string.
C++
#include <iostream> #include <string> int main() { std::string text = "Hello"; std::cout << text.[1]() << std::endl; return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a function that doesn't exist like count() or getSize()
✗ Incorrect
The length() function returns the number of characters in the string.
2fill in blank
mediumComplete the code to convert the string to uppercase using a loop.
C++
#include <iostream> #include <string> #include <cctype> int main() { std::string text = "hello"; for (int i = 0; i < text.length(); ++i) { text[i] = [1](text[i]); } std::cout << text << std::endl; return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-existent functions like toUpperCase or upper
✗ Incorrect
The toupper() function converts a character to uppercase.
3fill in blank
hardFix the error in the code to find the position of a character in the string.
C++
#include <iostream> #include <string> int main() { std::string text = "apple"; size_t pos = text.[1]('p'); std::cout << pos << std::endl; return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using JavaScript-like functions such as indexOf
✗ Incorrect
The find() function returns the index of the first occurrence of the character.
4fill in blank
hardFill both blanks to create a substring from index 1 to 3.
C++
#include <iostream> #include <string> int main() { std::string text = "banana"; std::string part = text.[1]([2], 3); std::cout << part << std::endl; return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
substring which is not a C++ string functionWrong starting index
✗ Incorrect
The substr() function extracts a substring starting at the given index. Here, starting at index 1 for length 3 gives "ana".
5fill in blank
hardFill all three blanks to replace 'cat' with 'dog' in the string.
C++
#include <iostream> #include <string> int main() { std::string text = "the cat sat"; size_t pos = text.[1]("cat"); if (pos != std::string::npos) { text.[2](pos, [3], "dog"); } std::cout << text << std::endl; return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
erase instead of replaceWrong length for replacement
✗ Incorrect
First, find() locates "cat". Then replace() replaces 3 characters starting at that position with "dog".