【发布时间】:2013-08-18 12:16:24
【问题描述】:
我想出的下面的程序用于检查两个字符串是否是字谜。它适用于小弦但适用于较大的弦(我试过:听过,入伍)它给了我一个“不!”
帮助!
#include<iostream.h>
#include<string.h>
#include<stdio.h>
int main()
{
char str1[100], str2[100];
gets(str1);
gets(str2);
int i,j;
int n1=strlen(str1);
int n2=strlen(str2);
int c=0;
if(n1!=n2)
{
cout<<"\nThey are not anagrams ! ";
return 0;
}
else
{
for(i=0;i<n1;i++)
for(j=0;j<n2;j++)
if(str1[i]==str2[j])
++c;
}
if(c==n1)
cout<<"yes ! anagram !! ";
else
cout<<"no ! ";
system("pause");
return 0;
}
【问题讨论】:
-
iostream.h是一个非常古老的非标准标头。而你正在使用 C++。使用std::cin读取std::string,因为gets很糟糕,即使在C 中也是如此,而且C 字符串在C++ 中通常较差(我假设您想要一个单词,因为它用于字谜)。使用std::sort对它们进行排序,然后进行比较。 -
你的算法是错误的,简单明了,和字符串的长度无关。尝试使用“aa”、“aa”。多想想。看在上帝的份上,不要使用
gets()。