判断字符串是否是回文C++
时间: 2023-12-01 20:42:05 浏览: 94
以下是C++判断字符串是否是回文的代码示例:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[101];
cin >> str;
int len = strlen(str);
bool isPalindrome = true;
for (int i = 0; i < len / 2; i++) {
if (str[i] != str[len - i - 1]) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
cout << "yes" << endl;
} else {
cout << "no" << endl;
}
return 0;
}
```
该代码首先读入一个字符串,然后使用一个布尔变量`isPalindrome`来记录该字符串是否是回文。接着使用一个循环遍历字符串的前一半字符,判断其是否与后一半字符对应位置的字符相同,如果不同则将`isPalindrome`设为`false`并跳出循环。最后根据`isPalindrome`的值输出结果。
相关问题
判断字符串是否为回文c++
可以使用双指针来判断一个字符串是否为回文。具体实现如下:
```c++
#include <iostream>
#include <string>
using namespace std;
bool isPalindrome(string s) {
int left = 0, right = s.size() - 1;
while (left < right) {
if (s[left] != s[right])
return false;
left++;
right--;
}
return true;
}
int main() {
string s;
cout << "请输入一个字符串:" << endl;
cin >> s;
if (isPalindrome(s))
cout << "是回文字符串" << endl;
else
cout << "不是回文字符串" << endl;
return 0;
}
```
该代码通过双指针遍历字符串,如果左右指针所指的字符不同,则说明不是回文字符串,直接返回 false;否则左右指针分别向中间移动。最后如果左右指针相遇,则说明是回文字符串,返回 true。
c++判断字符串是否是回文
在C++中,判断一个字符串是否是回文(即正读反读都一样的字符串),一种常见的方法是通过双指针技术,从两端向中间遍历,比较对应位置的字符是否相等。下面是一个简单的示例:
```cpp
#include <iostream>
#include <string>
bool isPalindrome(const std::string& str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str[left] != str[right]) {
return false; // 如果找到不匹配的字符,直接返回false
}
left++; // 左指针向右移动一位
right--; // 右指针向左移动一位
}
return true; // 没有发现不匹配,说明是回文
}
int main() {
std::string test_strs[] = {"level", "madam", "hello"};
for (const auto& str : test_strs) {
if (isPalindrome(str)) {
std::cout << str << " 是回文\n";
} else {
std::cout << str << " 不是回文\n";
}
}
return 0;
}
```
在这个例子中,`isPalindrome` 函数会检查输入的字符串,如果所有的字符都一一对应相等,则返回 `true`,否则返回 `false`。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.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)
![](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)
![](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)
![](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)