12345678910111213141516171819202122232425262728293031323334353637383940414243444546
#include <iostream> #include <iomanip> #define _USE_MATH_DEFINES #include <math.h> #include <string> using namespace std; int countSubstring(const string& str, const string& sub) { if (sub.length() == 0) return 0; int count = 0; for (size_t offset = str.find(sub); offset != std::string::npos; offset = str.find(sub, offset + sub.length())) { ++count; } return count; } int main() { int NumofVotes; cin >> NumofVotes; string input; int A = 0, B = 0; //must use getline to input entire line for (int AmountofTimes = 0; AmountofTimes <= NumofVotes; AmountofTimes++) { getline(cin, input); } A = countSubstring(input, "A"); B = countSubstring(input, "B"); if (A == B) cout << "Tie"; else if (A > B) cout << "A"; else cout << "B"; }//end main
std::count
12345678910111213
#include <iostream> #include <string> #include <algorithm> int main() { const std::string MyString = "abcasdfafghabcrty"; const char CharSearch = 'a'; std::size_t Count = std::count(MyString.begin(), MyString.end(), CharSearch); std::cout << "Count is " << Count << '\n'; return 0; }
1234567891011121314151617181920
#include <string> #include <iostream> int Count( const std::string & str, const std::string & obj ) { int n = 0; std::string ::size_type pos = 0; while( (pos = obj.find( str, pos )) != std::string::npos ) { n++; pos += str.size(); } return n; } int main() { std::string s = "How do you do at ou"; int n = Count( "ou", s ); std::cout << n << std::endl; }