C++ | Помогите доделать функцию что возвращает число вхождений подстроки
Предполагается что функция вернёт 2, а возвращает 3. Можно исправить?
int CountChar(string text, string text_char) {
int res = 0, check = 0;
int text_size = StrSize(text);
int char_size = StrSize(text_char);
for (int i = 0; i < text_size; i++) {
for (int j = 1; j < char_size; j++) {
if (text[i] == text_char[j]) {
if (text[i + j] == text_char[j + j]) {
res++;
}
}
}
}
return res;
}
int main() {
cout << CountChar("Hello_|_Poppy_|_", "_|_") << endl;
return 0;
}
Ответы (3 шт):
Автор решения: DaraHessesh
→ Ссылка
Мое предложение:
int CountChar(string text, string text_char) {
int res = 0, check = 0;
int text_size = StrSize(text);
int char_size = StrSize(text_char);
for (int i = 0; i < text_size; i++) {
if (text[i]==text_char[0]){
for (int j=0; j < char_size; j++){
if (text[i+j]==text_char[j]) {check++;}
};
if (check == char_size) {res++};
check = j;
};
};
return res;
};
int main() {
cout << CountChar("Hello_|_Poppy_|_", "_|_") << endl;
return 0;
};
Автор решения: Виктор
→ Ссылка
Вариант:
int CountChar(string text, string text_char) {
int res = 0, check = 0;
int text_size = text.length();
int char_size = text_char.length();
for (int i = 0; i < text_size; ) {
check=0;
for (int j = 0; j < char_size; j++) {
// Проверяем на совпадение
// и учитываем размер строки string text
if ( i+j < text_size && text[i+j] == text_char[j])
check++; // Совпал один символ
else
break;
}
if ( check == char_size ) { // Сколько символов совпало?
i += check; // Перемещаемся за совпадение
res++;
}
else
i++;
}
return res;
}
Автор решения: Slava
→ Ссылка
Как написано в документации к std::string есть метод std::string::find() если его использовать код станет сильно короче:
int CountChar( std::string text, std::string text_char ) {
int res = 0;
for( size_t p = 0; ( p = text.find( text_char, p ) ) != std::string::npos; ++res )
p += text_char.length();
return res;
}