21xrx.com
2025-03-27 17:40:57 Thursday
文章检索 我的文章 写文章
C++实现回文字符检查
2023-06-25 10:48:40 深夜i     11     0
C++ 回文 字符 检查 实现

回文字符是指一个字符串从左往右读和从右往左读结果是一样的字符串,比如“level”、“deified”等。在C++中,我们可以使用一些方法来实现回文字符的检查。

第一种方法是将字符串翻转后进行比对。这里我们可以使用一个for循环和swap函数来翻转字符串,并使用一个bool变量来记录是否是回文字符。具体代码如下:

#include <iostream>
#include <string>
using namespace std;
int main() {
  string str;
  bool isPalindrome = true;
  cout << "Enter a string: ";
  cin >> str;
  for (int i = 0; i < str.length() / 2; i++) {
    swap(str[i], str[str.length() - i - 1]);
  }
  for (int i = 0; i < str.length(); i++) {
    if (str[i] != str[str.length() - i - 1])
      isPalindrome = false;
      break;
    
  }
  if (isPalindrome)
    cout << "It is a palindrome!" << endl;
   else
    cout << "It is not a palindrome!" << endl;
  
  return 0;
}

第二种方法是利用一个while循环,从字符串的头尾同时开始比较字符是否相等,如果有一个不相等就说明不是回文字符。具体代码如下:

#include <iostream>
#include <string>
using namespace std;
int main() {
  string str;
  bool isPalindrome = true;
  cout << "Enter a string: ";
  cin >> str;
  int i = 0, j = str.length() - 1;
  while (i < j) {
    if (str[i] != str[j])
      isPalindrome = false;
      break;
    
    i++;
    j--;
  }
  if (isPalindrome)
    cout << "It is a palindrome!" << endl;
   else
    cout << "It is not a palindrome!" << endl;
  
  return 0;
}

无论是哪种方法,只要字符是回文字符,最终输出的结果都是“It is a palindrome!”。C++中的两种实现方法都很简单易懂,非常适合初学者完成相关实践。

  
  

评论区