【发布时间】:2014-02-02 04:11:12
【问题描述】:
我正在尝试用 C++ 编写一个程序,它将一个字符串作为标准 cin 输入的输入,并确定输入是否为回文。我无法以任何方式更改字符串,也无法复制它。
代码必须包含类似bool isPalindrome( const char* x){}
下面列出了我的尝试。
#include <cctype>
#include <iostream>
#include <string>
using namespace std;
bool isPalindrome( const char* x)
{
string str = *x;
int n = str.length();
for (int i = 0; i < n; ++i)
{
int j = 0;
while (isalpha(str[i]))
{
if (isalpha(str[n-j-1]))
{
if (tolower(str[i]) == tolower(str[n-j-1]))
return true;
else
return false;
}
j += 1;
}
}
return true;
}
int main()
{
string str;
cout << "Enter your string: ";
getline (cin, str);
const char * x ;
x = &str;
if (isPalindrome(x) == true)
{
cout << "Yes it is!" << endl;
}
else
{
cout << "No, it's not." << endl;
}
cout << str << endl;
return 0;
}
我不是最好的 C++ 程序员,指针的使用对我来说仍然有点困惑。参数const char * x 是否意味着输入被初始化为值不变的指针?任何帮助是极大的赞赏!
编辑:我忘了提...输入可能包含标点符号,但仍然可以是回文。例如“女士,我是亚当!”是回文。但是我不能从字符串中删除标点符号,因为不允许更改字符串。
【问题讨论】:
-
这个任务根本不需要指针。
-
@user3261977:一种明显的方法是使用迭代器。
-
为什么不能复制字符串?无论如何,只需通过递增迭代器来跳过标点和空格
标签: c++ pointers palindrome