I have a function definition
int searchChar(char, string)
{/* ... */}
I do not know how to use it. I have to return the number of times a char appears in a string. I thought that we are suppose to use char and string with a variable. I do not know how to use it in this way.
答案 0 :(得分:1)
#include <iostream>
#include <string>
int searchChar(char /*toFind*/, std::string /*str*/);
int main()
{
std::string s = "hello world";
std::cout << searchChar('l', s); // displays '3'
return 0;
}
int searchChar(char toFind, std::string str)
{
int count = 0;
for(size_t i = 0; i < str.length(); ++i)
{
if (str[i] == toFind)
++count;
}
return count;
}
/*
Alternatively:
int searchChar(char toFind, std::string str)
{
int count = 0;
for(std::string::iterator iter = str.begin(); iter != str.end(); ++iter)
{
if (*iter == toFind)
++count;
}
return count;
}
*/
/*
Alternatively:
int searchChar(char toFind, std::string str)
{
int count = 0;
for(char ch : str)
{
if (ch == toFind)
++count;
}
return count;
}
*/
/*
Alternatively:
#include <algorithm>
int searchChar(char toFind, std::string str)
{
return std::count(str.begin(), str.end(), toFind);
}
*/