Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to check if the pattern exists in the text using the find() method.
DSA C++
std::string text = "hello world"; std::string pattern = "world"; if (text.[1](pattern) != std::string::npos) { std::cout << "Pattern found" << std::endl; } else { std::cout << "Pattern not found" << std::endl; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using substr() instead of find() to search for a pattern.
Using compare() which compares strings but does not search for substrings.
✗ Incorrect
The find() method returns the starting index of the pattern if found, otherwise std::string::npos.
2fill in blank
mediumComplete the code to extract the substring from text starting at index 3 with length 4.
DSA C++
std::string text = "substring"; std::string sub = text.[1](3, 4); std::cout << sub << std::endl;
Attempts:
3 left
💡 Hint
Common Mistakes
Using find() which searches for a substring but does not extract it.
Using replace() which modifies the string instead of extracting.
✗ Incorrect
The substr() method extracts a substring starting at the given index with the specified length.
3fill in blank
hardFix the error in the code to correctly compare the substring with the pattern.
DSA C++
std::string text = "example"; std::string pattern = "amp"; if (text.substr(2, 3).[1](pattern) == 0) { std::cout << "Match found" << std::endl; } else { std::cout << "No match" << std::endl; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using find() which returns index, not a comparison result.
Using substr() incorrectly inside the if condition.
✗ Incorrect
The compare() method returns 0 if the two strings are equal.
4fill in blank
hardFill both blanks to create a loop that finds all occurrences of pattern in text.
DSA C++
std::string text = "abracadabra"; std::string pattern = "abra"; size_t pos = 0; while ((pos = text.[1](pattern, pos)) != std::string::npos) { std::cout << "Found at " << pos << std::endl; pos [2] pattern.length(); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using replace() instead of find() in the loop condition.
Using -= instead of += causing infinite loop or wrong position.
✗ Incorrect
Use find() to locate the pattern starting from pos, then increment pos by pattern length to continue searching.
5fill in blank
hardFill all three blanks to create a map of each word to its length for words longer than 3 characters.
DSA C++
std::vector<std::string> words = {"code", "is", "fun", "and", "powerful"};
std::map<std::string, int> lengths;
for (const auto& word : words) {
if (word.[2]() [3] 3) {
lengths[word] = [1];
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using <=' instead of > causing wrong filtering.
Using word.length without parentheses causing syntax error.
✗ Incorrect
Use word.length() to get length, call length() method on word, and compare with > 3 to filter longer words.
