首页 > 解决方案 > 找出两个字符串输入是否是字谜,忽略空格、标点符号和数字

问题描述

我试图找出两个字符串输入是否是一个字谜。程序必须忽略空格、标点符号和数字。

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

#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 字符串程序                                                                                                                           
输入一些东西-> kkk                                                                                                                                  
输入一些东西-> kkk   
两个字符串不是彼此的字谜

标签: c++validationanagram

解决方案


您在函数return true;末尾缺少 a 。areAnagram


推荐阅读