找出两个字符串输入是否是变位词,忽略空格、标点符号和数字

Find out if two string inputs are anagram, ignoring white spaces, punctuation, and numbers

我正在尝试确定两个字符串输入是否是变位词。该程序必须忽略空格、标点符号和数字。

我有一个函数可以验证输入流中的每个字符。当我 运行 程序时,它会在我输入第一个字符串后放置两个空格。它还会给出错误的输出。

#include <iostream>
#include <bits/stdc++.h>
#include <string>
#define No_of_chars 26

using namespace std;
const int SIZE = 26;
int count1[No_of_chars]={0};
               
// finds the strings are anagram
bool areAnagram(string str1, string str2)
{
    // Get lengths of both strings
    int n1 = str1.length();
    int n2 = str2.length();

    // If length of both strings is not same, then they cannot be anagram
    if (n1 != n2)
        return false;

    // Sort both the strings
    sort(str1.begin(), str1.end());
    sort(str2.begin(), str2.end());

    // Compare sorted strings
    for (int i = 0; i < n1; i++)
        if (str1[i] != str2[i])
            return false;
}

// validate each character in the input string
void validateCharacter(string sentence)
{
    char ch;
    int count = 0;

    cin.get(ch);
    while(ch >= ' ' && count < SIZE)
    {
        if (isalpha(ch))
        {
            cin.ignore();
        }

        sentence=ch;

        count++;
        cin.get(ch);
    }
}

int main()
{
    string s1;
    string s2;
    cout<< "Csci Anagram Strings Program"<<endl;

    cout << "enter something ->";
    validateCharacter(s1);

    cout << "enter something ->";
    validateCharacter(s2);

    if(areAnagram(s1, s2))
        cout << "The two strings are anagram of each other";
    else
        cout << "The two strings are not anagram of each other";

    return 0;
}

输出错误:

Csci Anagram Strings Program                                                                                                                           
enter something ->kkk                                                                                                                                  
enter something ->kkk   
The two strings are not anagram of each other

您的 areAnagram 函数末尾缺少 return true;