【发布时间】:2020-12-19 01:13:54
【问题描述】:
我试图找出两个字符串输入是否是一个字谜。程序必须忽略空格、标点符号和数字。
我有一个函数可以验证输入流中的每个字符。当我运行程序时,它会在我输入第一个字符串后放置两个空格。它也会给出错误的输出。
#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 两个字符串不是彼此的字谜【问题讨论】:
-
areAnagram 在任何情况下都不返回 true 吗?如果字符串是字谜,似乎不会返回任何内容。
-
sentence=ch应该做什么?此外,通过引用而不是值传递它(或完全删除参数并返回 std::string 作为函数结果)。并且请不要发送垃圾语言标签(已修复 - 它是 C++,而不是 C)。 -
另外,排序会给你 nlogn 的复杂性。您可以单步执行 n 并使用 hashmap 来计算每个字母的数量。
-
哦,我的 anagram 函数没有返回 true。谢谢,但现在每个输入都返回 true。可能与字符验证有关。我正在使用 cin.get() 来处理每个字符,但是当我在收到提示之前按键盘上的 Enter 键时得到一个很大的空间对于第二个字符串,为什么? @Paul Sander 好的。
-
我建议使用
cin >> my_string_variable,然后删除不需要的字符。
标签: c++ validation anagram