#include <iostream> using namespace std; #define STR_LEN 80 //读入一行存入字符数组str,长度不超过maxLength void readline(char str[], int maxLength); //判断字符串str是否是回文 bool isPalindrome(char str[]); int main() { char str[STR_LEN + 1]; // cout << "Please input a string with length <= " << STR_LEN << ":"; readline(str, STR_LEN); if (isPalindrome(str)) { cout << "Yes" << endl; } else { cout << "No" << endl; } return 0; } //读入一行存入字符数组str,长度不超过maxLength void readline(char str[], int maxLength) { int i = 0; while (i < maxLength) { char ch = cin.get(); if (ch != '\n' && ch != '\r') { str[i] = ch; } else { break; } i++; } str[i] = '\0'; } //判断字符串str是否是回文 bool isPalindrome(char str[]) { /********* Begin *********/ int i=0; while(str[i]!='\0') { i=i+1; } cout<<i<<endl; char q[i]; for(int j=0 ; j<i; j++) { q[j]=str[i-1-j]; } if (q[0]>='a'and q[0]<='z') { q[0]=q[0]-32; } else if (q[i-1]>='A' and q[i-1]<='Z') { q[i-1]=q[i-1]+32; } int t; for(int j=0 ; j<i; j++) { if (q[j]==str[j]) { t=0; } else { t=1; } } if (t==0) { cout<<"Yes"<<endl; } else if(t==1) { cout<<"No"<<endl; } /********* End *********/ }这个代码哪里有问题
时间: 2024-01-07 07:02:22 浏览: 26
这个代码有几个问题:
1. 在判断回文时,只需要比较原字符串与反转后的字符串是否相同即可,不需要再分别比较每个字符。
2. 在转换大小写时,只需要判断首尾字符是否需要转换即可,不需要分别判断首尾字符。
下面是修改后的代码:
```c++
#include <iostream>
using namespace std;
#define STR_LEN 80
void readline(char str[], int maxLength);
bool isPalindrome(char str[]);
int main() {
char str[STR_LEN + 1];
readline(str, STR_LEN);
if (isPalindrome(str)) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
return 0;
}
void readline(char str[], int maxLength) {
int i = 0;
while (i < maxLength) {
char ch = cin.get();
if (ch != '\n' && ch != '\r') {
str[i] = ch;
} else {
break;
}
i++;
}
str[i] = '\0';
}
bool isPalindrome(char str[]) {
int len = 0;
while (str[len] != '\0') {
len++;
}
char reversed[len + 1];
for (int i = 0; i < len; i++) {
reversed[i] = str[len - i - 1];
}
reversed[len] = '\0';
if (strcmp(str, reversed) == 0) {
return true;
} else {
return false;
}
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)