21xrx.com
2024-09-20 01:01:36 Friday
登录
文章检索 我的文章 写文章
C++实现回文字符检查
2023-07-02 04:51:25 深夜i     --     --
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++中的两种实现方法都很简单易懂,非常适合初学者完成相关实践。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复