frequency of a substring in a string c++
To find the frequency of a substring in a string in C++, you can follow these steps:
- Initialize a counter variable to 0. This variable will keep track of the frequency of the substring.
- Use a loop to iterate through the string. The loop will start from 0 and end at the length of the string minus the length of the substring. This ensures that the loop doesn't go beyond the end of the string.
- Inside the loop, use the
substr
function to extract a substring from the original string. Thesubstr
function takes two parameters: the starting index and the length of the substring. The starting index will be the loop variable, and the length will be the length of the substring. - Check if the extracted substring is equal to the desired substring. You can use the
==
operator to compare the two strings. - If the extracted substring is equal to the desired substring, increment the counter variable by 1.
- After the loop is finished, the counter variable will contain the frequency of the substring in the string.
Here's a code example that demonstrates this approach:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, Hello, Hello, World!";
std::string substring = "Hello";
int frequency = 0;
for (size_t i = 0; i <= str.length() - substring.length(); i++) {
std::string extracted = str.substr(i, substring.length());
if (extracted == substring) {
frequency++;
}
}
std::cout << "Frequency of substring: " << frequency << std::endl;
return 0;
}
In this example, the string "Hello, Hello, Hello, World!" is searched for the substring "Hello". The frequency of the substring is then printed to the console.