【发布时间】:2017-04-27 13:53:28
【问题描述】:
对于任何能够帮助我解决这个问题的人。我正在创建一种方法来比较两个字符串并检测它们是否是字谜。字谜是具有相同字母的两个字符串,尽管它们的顺序可能不同。例如“listen”和“iltsen”是字谜。
我决定将字符串分解为 char 数组。我知道它工作正常,因为我在每个数组元素上使用 cout 对其进行了测试。接下来是哪里出错了。我尝试使用每个字符的 ASCII 值并将其添加到每个数组的变量中。这意味着如果值匹配,则它们必须是字谜。
但是,无论出于何种未知原因,它都无法正常工作。我发现它为一个数组读取索引 0 两次,而不是另一个数组。我很困惑,无法解释。我完全不知道这是怎么回事。我尝试了多种不同的解决方案,但没有找到问题所在。如果有人知道这里发生了什么,我将不胜感激。
-谢谢!
#include "stdafx.h"
#include <iostream>
#include <string>
#include <math.h>
#include <iomanip>
#include <cctype>
#include <vector>
using namespace std;
bool isAnagram(string s1,string s2)
{
static char firstString[] = { 'c' };
static char secondString[] = { 'c' };
int size = s1.length();
static int count1 = 0;
static int count2 = 0;
cout << s1 << endl;
cout << s2 << endl;
if (s1.length() == s2.length())
{
for (int i = 0; i < size; i++)
{
firstString[i] = s1.at(i);
cout << i;
}
for (int i = 0; i < size; i++)
{
secondString[i] = s2.at(i);
cout << i;
}
cout << endl;
for (int i = 0; i < size; i++)
{
count1 = count1 + (int)firstString[i];
cout << "first" << i << ": " << firstString[i] << " = " << (int)firstString[i] << endl;
count2 = count2 + (int)secondString[i];
cout << "second" << i << ": " << secondString[i] << " = " << (int)secondString[i] << endl;
}
cout << count1 << " and " << count2 << endl;
if (count1 == count2)
return true;
}
else
return false;
count1 = 0;
count2 = 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
static char end;
do
{
string s1;
string s2;
cout << "Please enter the first string: ";
cin >> s1;
cout << endl << "Please enter the second string: ";
cin >> s2;
bool result = isAnagram(s1, s2);
static string resultString;
if (result == true)
resultString = "True";
else
resultString = "False";
cout << endl << "Anagram test result: " << resultString << endl;
cout << endl << "enter E for end or any other key to run again: ";
cin >> end;
cout << "----------------------------------------" << endl;
} while (end != 'e' && end != 'E');
return 0;
}
【问题讨论】:
-
为什么数组和计数是静态的?你应该使用 std::vectors 而不是数组
-
firstString[i] = s1.at(i);你不能这样做:缓冲区太小了。 -
已经存在于标准库中:std::is_permutation
-
我将它们设为静态,以便考虑到它们超出范围,可以在循环内修改它们的值。这是一个正确的假设吗?还有让,谢谢你的回复。有没有办法将缓冲区设置为更大的大小?保罗,也感谢您的回复。您提供的链接很有帮助。
-
你需要检查s1和s2的长度是否相同。之后将您的两个 char 数组分配给该大小。
标签: c++ arrays string ascii anagram