C++ 查看两个字符串是否为字谜[C+;+;]

C++ 查看两个字符串是否为字谜[C+;+;],c++,arrays,string,histogram,anagram,C++,Arrays,String,Histogram,Anagram,我将编写一个程序,将2个字符串放入一个名为“build_histogram”的函数中,并构建一个int数组,该数组记录每个字母在每个字符串中出现的次数,然后比较数组,如果它们相等,则它们是anagram。说明中指出,我们将忽略所有符号(例如!、空格、等),并且不区分大小写 #include <iostream> #include <string> #include <cctype> using namespace std; void build_histog

我将编写一个程序,将2个字符串放入一个名为“build_histogram”的函数中,并构建一个int数组,该数组记录每个字母在每个字符串中出现的次数,然后比较数组,如果它们相等,则它们是anagram。说明中指出,我们将忽略所有符号(例如!、空格、等),并且不区分大小写

#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;
}
#包括
#包括
#包括
使用名称空间std;
无效构建直方图(整数字母[],字符串s){
对于(int i=0;i这不是你的全部解决方案,但它肯定是一个开始

您的
字母[]
数组只有索引0到25,因此您希望将字母转换为对应于0-25

下面是一个简单的方法:

void build_histogram(int* letters[], string s) {

   for(int i = 0; i < s.length(); i++) {
      char currLetter = s[i];
      ///force letter to become lowercase
      currLetter = tolower(currLetter);

      ///make letter an ASCII value
      int index = currLetter - 97;//subtract 97 to get a range from 0 to 25
      letters[index]++;
   }
}
void build_直方图(int*字母[],字符串s){
对于(int i=0;i
此实现将所有字母转换为小写形式

此外,
'a'
的实例数将存储在索引0中,
'z'
将存储在索引25中


希望这能帮助您走上正确的道路!

如果两个字符串的长度相同,那么它们就是字谜,而另一个字符串的长度是
std::is_permutation()

我们可以编写一个函数来检查两个字符串是否是这样的字谜:

bool is_anagram(const std::string& s1, const std::string& s2) {
    return s1.size() == s2.size() &&
        std::is_permutation(std::begin(s1), std::end(s1), 
            std::begin(s2), std::end(s2));
}

A
的ASCII值是64+1=65。
A
的ASCII值是64+32+1=97。这与
build\u histogram
函数如何工作?很抱歉,我们也忽略大小写。我要编写的函数应该只计算每个字母出现的次数并将其存储在数组中。示例:数组[0]将存储“a”数组[1]将存储“b”重新考虑
int*historogramx[26]
指向
int
的指针数组对您没有多大好处。此外,强烈建议您初始化这些数组值。如果您不知道起始值,则很难进行任何精确计数。
historogram1==historogram2
这是比较数组的错误方法。您可以在索引处比较相应的值两个数组的es或use
memcmp(historogram1,historogram2,sizeof(historogram1)*sizeof(int))==0
谢天谢地。我开始写这样的东西,我希望我的方向是正确的!谢谢!但我的指令说程序忽略空格和符号。(示例输入1:“igno r e!pu,c”输入2:“erognpcui”;虽然它们的长度不同,包含不同的符号,但程序将返回它们是字谜。)然后在检查之前删除两个字符串中的所有空格。我们的教授有一个特定的方法让我们写它,否则我们将得不到学分…我们还没有学会删除空格,所以我认为我无法做到这一点并获得满分(我们的老师很蹩脚,宁愿我们“他的”去做)方法,即使有更好的方法。)
bool is_anagram(const std::string& s1, const std::string& s2) {
    return s1.size() == s2.size() &&
        std::is_permutation(std::begin(s1), std::end(s1), 
            std::begin(s2), std::end(s2));
}