Complete the code to get the length of the string.
#include <iostream> #include <string> int main() { std::string text = "Hello"; std::cout << text.[1]() << std::endl; return 0; }
The length() function returns the number of characters in the string.
Complete the code to convert the string to uppercase using a loop.
#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; }
The toupper() function converts a character to uppercase.
Fix the error in the code to find the position of a character in the string.
#include <iostream> #include <string> int main() { std::string text = "apple"; size_t pos = text.[1]('p'); std::cout << pos << std::endl; return 0; }
The find() function returns the index of the first occurrence of the character.
Fill both blanks to create a substring from index 1 to 3.
#include <iostream> #include <string> int main() { std::string text = "banana"; std::string part = text.[1]([2], 3); std::cout << part << std::endl; return 0; }
substring which is not a C++ string functionThe substr() function extracts a substring starting at the given index. Here, starting at index 1 for length 3 gives "ana".
Fill all three blanks to replace 'cat' with 'dog' in the string.
#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; }
erase instead of replaceFirst, find() locates "cat". Then replace() replaces 3 characters starting at that position with "dog".
