如何比较字符串以查看在"$"之前输入的字符是否等于它之后的字符?
How to Compare a string to see if the characters entered before '$' are equal to the ones after it?
我一直在为一本书实现一个算法,如下所示:
L={w$w':w可能是一个空字符串,而不是$w'=reverse(w)}
根据书中的伪代码,我为我的程序编写了代码,该代码将使用您输入的字符串,例如(a$a,ABC$CBA),并比较$前后的字符,以确定它们是否是回文。我完全按照书中的指示编写了代码,但程序运行不正常。无论我输入什么,它总是返回false。
我不知道我做错了什么。
这是我写的代码:
#include <iostream>
#include "stack.h"
#include <string>
using namespace std;
bool isInLanguage(string aString)
{
Stack<char> aStack;
int i = 0;
// ch is aString[i]
while( aString[i] != '$')
{
aStack.push(aString[i]);
++i;
}
//skip the $
++i;
//match the reverse of w
bool inLanguage = true; // assume string is in language
while(inLanguage && i < aString.length())
{
char stackTop;
aStack.pop(stackTop);
if(stackTop == aString[i])
++i; //characters match
else
//top of stack is not aString[i]
inLanguage = false; //reject string
if(aStack.isEmpty())
{
//pop failed, stack is empty. first half of string
//is shorter than second half)
inLanguage = false;
} // end if
} // end while
if (inLanguage && aStack.isEmpty())
return true;
else
return false;
} // end isInLanguage
int main()
{
string str;
bool boolean;
cout << "Enter a string to be checked by the algorithm : ";
cin >> str;
boolean = isInLanguage(str);
if (boolean == true)
cout << "The string is in language.n";
else
cout << "The string is not in language.n";
return 0;
}
即使在弹出字符串中的最后一个字符后,您也要检查if(aStack.IsEmpty())
,它将返回true,从而将inLanguage
设置为false
。因此,即使字符串是回文,在弹出最后一个字符后,您仍然将inLanguage
设置为false
。
在pop操作的while循环之前,您没有重新初始化变量i=0。
....
++i;
//match the reverse of w
bool inLanguage = true; // assume string is in language
while(inLanguage && i < aString.length())
{
.....
根据您的代码,while循环中的条件i < aString.length
将始终为false。
在while循环之前试试这个。。
i = 0;
正如Naveen所说,while
循环中的逻辑是错误的。考虑一下$a:的简单情况会发生什么
push 'a' in the stack
skip $
pop 'a' and compare with 'a' -> inLanguage == true
stack is empty -> inLanguage == false
这显然不是你想要的。您需要在循环的条件下测试堆栈大小。我会把循环简化成这样:
while (i < aString.size() && !aStack.isEmpty()) {
char stackTop;
aStack.pop(stackTop);
if(stackTop != aString[i]) break;
++i;
}
if (i == aString.size() && aStack.isEmpty())
return true;
else
return false;
相关文章:
- 比较字符数组
- 比较 c++ 中的字符数组
- 将 if 语句中的字符与 or 进行比较
- 将字符串字节与字符 c++ 进行比较
- 如何将32位字符与内联assembelyc++中的32位字符进行比较
- 与C++中不止一个字符进行比较
- 将字符串指针与 NULL 以及 NULL 字符进行比较的目的
- 如果我在与字符进行比较之前没有明确将 int 转换为字符,这有关系吗?
- 位字段的大小与字符的比较
- c++Unicode字符串与易混淆字符的比较.例如(U 0054)应为==(U03A4)等
- 将缓冲区与字符进行比较是无效的
- C++:如何查看正在读取的文件的下一个字符以比较字符?
- TinyXML无法将属性与字符进行比较
- 将字符串中的字符与给定的字符进行比较
- 将字符串中的元素与字符进行比较时出现未知错误
- C++ 无法将取消引用的字符指针与字符进行比较
- Qt中的第一个简单if语句:两个字符的比较
- String.at() 不与字符进行比较
- 将字符与西班牙语字符进行比较
- 不区分大小写的前n个字符字符串比较