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

时间:2017-02-24 05:04:32

标签: c++ arrays string histogram anagram

我要编写一个程序,它将占用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;
}

这就是我到目前为止所做的,但无论我输入什么字符串,除了&#34;输入两个字符串之外,我无法让程序打印任何字符串。&#34;

修改

所以现在这是我的代码......它在每个字符串中正确计算字符数,现在唯一的问题是&#34; if else&#34;底部的陈述仍然没有认识到阵列是相同的,而且当符号像'&#39;!&#39;在字符串中。

#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;
}

0 个答案:

没有答案