Hint: Substring search means finding a smaller string inside a bigger one [OK]
Common Mistakes:
Confusing substring search with sorting or reversing strings
Thinking substring search counts characters instead of finding patterns
2. Which of the following is the correct syntax to check if string pattern is a substring of string text in C++?
easy
A. if (text.find(pattern) != std::string::npos) { /* found */ }
B. if (pattern.contains(text)) { /* found */ }
C. if (text.indexOf(pattern)) { /* found */ }
D. if (text.search(pattern) == true) { /* found */ }
Solution
Step 1: Recall C++ substring search syntax
In C++, std::string::find returns the position of the substring or std::string::npos if not found.
Step 2: Analyze each option
if (text.find(pattern) != std::string::npos) { /* found */ } uses text.find(pattern) != std::string::npos, which is correct. Others use invalid or non-existent methods.
Final Answer:
if (text.find(pattern) != std::string::npos) { /* found */ } -> Option A
Quick Check:
Use find() and compare with npos [OK]
Hint: Use text.find(pattern) != npos to check substring [OK]
Common Mistakes:
Using methods like contains or indexOf which don't exist in std::string
Comparing find() result directly to true or false
3. What will be the output of the following C++ code?