0
0
DSA C++programming~30 mins

Count Words with Given Prefix in DSA C++ - Build from Scratch

Choose your learning style9 modes available
Count Words with Given Prefix
📖 Scenario: You are building a simple program to help a bookstore find how many book titles start with a certain prefix. This helps the store quickly count books by categories or themes.
🎯 Goal: Create a program that counts how many words in a list start with a given prefix.
📋 What You'll Learn
Create a vector of strings called words with the exact values: "apple", "app", "application", "banana", "band"
Create a string variable called prefix and set it to "app"
Use a for loop with variable word to iterate over words
Inside the loop, use word.compare(0, prefix.size(), prefix) == 0 to check if word starts with prefix
Create an integer variable count to count how many words start with prefix
Print the value of count at the end
💡 Why This Matters
🌍 Real World
Counting words with a specific prefix is useful in search engines, autocomplete features, and organizing data by categories.
💼 Career
This skill helps in software development roles involving text processing, search optimization, and building user-friendly interfaces.
Progress0 / 4 steps
1
Create the list of words
Create a vector of strings called words with these exact entries: "apple", "app", "application", "banana", "band"
DSA C++
Hint

Use std::vector<std::string> and initialize it with the given words inside curly braces.

2
Set the prefix to search
Create a string variable called prefix and set it to "app"
DSA C++
Hint

Use std::string prefix = "app"; to create the prefix variable.

3
Count words starting with the prefix
Create an integer variable called count and set it to 0. Use a for loop with variable word to iterate over words. Inside the loop, use word.compare(0, prefix.size(), prefix) == 0 to check if word starts with prefix. If yes, increase count by 1.
DSA C++
Hint

Use a range-based for loop and the compare method of std::string to check the prefix.

4
Print the count result
Print the value of count using std::cout
DSA C++
Hint

Use std::cout << count << std::endl; to print the count.