我正在尝试编写一个循环遍历字符串并计算每个字母被使用了多少的程序。问题是我无法让数组正确保存它。非常感谢任何帮助。
int main()
{
string textRad = "";
int histogram[ANTAL_BOKSTAVER];
getline(cin, textRad);
berakna_histogram_abs(histogram, textRad);
cout << histogram[0] << endl;
cout << histogram[2];
return 0;
}
void berakna_histogram_abs(int histogram[], string textRad)
{
for(int i = 0; i < ANTAL_BOKSTAVER; i++)
{
histogram[i] = 0;
}
for(int i = 0; i < textRad.length(); i++)
{
for(int j = 0; j < ANTAL_BOKSTAVER; j++)
{
int antal = 0;
string alfabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if(char(toupper(textRad.at(i))) == alfabet.at(j))
{
antal++;
}
histogram[j] = antal;
}
}
}
最佳答案
这里考虑到 Javid 和 Tjofras 的回答是一个完整、更简单、更安全的示例:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
void berakna_histogram_abs(std::vector<int>& histogram, const std::string& textRad);
int main() {
const int ANTAL_BOKSTAVER = 26; //Assumed value.
std::string textRad;
std::vector<int> histogram(ANTAL_BOKSTAVER, 0);
std::getline(std::cin, textRad);
std::transform(textRad.begin(), textRad.end(), textRad.begin(), toupper);
berakna_histogram_abs(histogram, textRad);
std::cout << histogram[0] << std::endl;
std::cout << histogram[2];
return 0;
}
void berakna_histogram_abs(std::vector<int>& histogram, const std::string& textRad) {
static std::string alfabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::size_t s = alfabet.length();
for(std::size_t i = 0; i < s; ++i) {
histogram[i] = std::count(test_string.begin(), test_string.end(), alfabet[i]);
}
}
关于c++ - 无法让数组正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18422387/