-4

How can I count the number of occurrences of a user inputed element in a string? Example:

Input: adseddsdf Input: a Output: 1

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
Ico
  • 1
  • 1
  • 2
    What do you think you can do? What have you tried to do? – ChrisMM Dec 30 '19 at 14:45
  • @Ico if you can clarify your question, you are welcome to [edit] it. – Drew Dormann Dec 30 '19 at 15:06
  • #include using namespace std; int main() { string str1; string str2="1"; cin>>str1; str1.replace(2,1,str2); cout< – Ico Dec 30 '19 at 15:48
  • This should be of use: https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – eerorika Dec 30 '19 at 16:12
  • 1
    You've edited this question to change it to an entirely different one. That is not appropriate here. I would suggest that you revert your edit to go back to the original question and then accept the correct answer to your original question given by Nick Khrapov. If you want to ask this new question, do so as a new question. – Avi Berger Dec 30 '19 at 18:29
  • 1
    I have rolled back the edits that invalidated the supplied answer. – Drew Dormann Dec 30 '19 at 22:33

1 Answers1

1

You can count it yourself or use stl

#include <algorithm>
#include <string>

int main()
{
    constexpr char chFind = 'a';
    std::string str = "abcabca";

    // first solution
    size_t num1 = 0;
    for(size_t i = 0; i < str.size(); i++)
        if (str[i] == chFind)
            num1++;

    // second solution
    size_t num2 = std::count(str.begin(), str.end(), chFind);

    return 0;
}
n0lavar
  • 113
  • 6