【发布时间】:2017-07-14 20:12:51
【问题描述】:
我要编写一个程序,它将接受 2 个字符串,将它们放入一个名为“build_histogram”的函数中,并构建一个 int 数组来计算每个字母在每个字符串中出现的次数,然后比较这些数组,如果它们相等,那么它们是字谜。说明声明我们要忽略所有符号(例如!、空格、_ 等),并且不区分大小写。
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
void build_histogram(int letters[], string s) {
for(int i = 0; i < s.length(); i++) {
letters[s[i]]++;
}
}
int main()
{
string s1, s2;
int* histogram1[26];
int* histogram2[26];
cout << "Enter two strings." << endl;
getline(cin, s1);
getline(cin, s2);
build_histogram(histogram1[26], s1);
build_histogram(histogram2[26], s2);
if(histogram1 != histogram2) {
cout << "They are not anagrams." << endl;
}
else {
cout << "They are anagrams!" << endl;
}
return 0;
}
这是我目前所拥有的,但无论我输入什么字符串,除了“输入两个字符串”之外,我无法让程序打印任何内容。
编辑
所以这是我现在的代码...它正确计算每个字符串中的字符数,现在唯一的问题是底部的“if else”语句仍然无法识别数组是相同的,也像“!”这样的符号很难在字符串中。
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
void build_histogram(int letters[], string s) {
for(int i = 0; i < s.length(); i++) {
char currLetter = s[i];
currLetter = tolower(currLetter);
int index = currLetter - 97;
letters[index]++;
}
}
int main()
{
string s1, s2;
int histogram1[26] = {0};
int histogram2[26] = {0};
cout << "Enter two strings." << endl;
getline(cin, s1);
getline(cin, s2);
build_histogram(histogram1, s1);
build_histogram(histogram2, s2);
if (histogram1 == histogram2) {
cout << "They are not anagrams." << endl;
} else {
cout << "They are anagrams!" << endl;
}
return 0;
}
【问题讨论】:
-
A的 ASCII 值是 64+1 = 65。a的 ASCII 值是 64+32+1 = 97。build_histogram函数是如何工作的? -
对不起,我们也忽略大小写。我要编写的函数应该只计算每个字母出现的次数并将其存储在数组中。例如:array[0] 将存储“a” array[1] 将存储“b”
-
重新考虑
int * histogramX[26];指向int的指针数组对您没有多大用处。此外,强烈建议初始化这些数组值。如果您不知道起始值,则很难进行准确的计数。 -
histogram1 == histogram2这是比较数组的错误方法。您可以比较两个数组索引处的相应值,也可以使用memcmp(histogram1, histogram2, sizeof(histogram1)*sizeof(int)) == 0
标签: c++ arrays string histogram anagram