给定一个string 字符串strArr,和一个char字符c,返回c在strArr中出现的个数。
用一个map<char,int>记录字符和出现的次数。谈不上什么算法,基本就是coding.
1.char c=strArr[i]: //类型转换string->char
2.int len=strArr.length(); //数组长度 strArr.size() 也可以获得长度
3.map<char ,int> word_count; //
赋值word_count[c]++; //map赋值
查值auto it = word_count.find(c);//查key value
上代码
#include <string>
#include <vector>
#include <iostream>
#include <map>
using namespace std;
int getStrNum(string strArr, char c)
{
int m_rc = 0;
// strArr = "abcdefgaaaaccc";
map<char ,int> word_count;
for (int i = 0; i < strArr.length(); i++)
{
char c1 = strArr[i];
word_count[c1]++;
}
for (auto it = word_count.begin(); it != word_count.end(); it++)
{
cout << "[" << it->first << "] = " << it->second << endl;//iter->first:key,iter->second:value
}
cout << "******************" << endl;
auto it1 = word_count.find(c);
cout << "[" << it1->first << "] = " << it1->second << endl;
m_rc = it1->second;
return m_rc;
}