21xrx.com
2024-09-20 01:06:26 Friday
登录
文章检索 我的文章 写文章
如何判断一个字符串是否为回文串 - c++语言编写
2023-06-28 10:57:48 深夜i     --     --
字符串 回文串 判断 c++编写

回文串是指正着读和倒着读都一样的字符串。例如,"level"、"racecar"、"noon"都是回文串。在C++语言中,判断一个字符串是否为回文串可以采用以下步骤:

1. 定义一个字符串变量并保存输入的字符串


string str;

cin >> str;

2. 定义两个指针,一个指向字符串的开头,一个指向字符串的结尾


int start = 0;

int end = str.length() - 1;

3. 循环比较两个指针所指向的字符是否相同,如果不同,则该字符串不是回文串


bool isPalindrome = true;

while (start < end) {

 if (str[start] != str[end])

  isPalindrome = false;

  break;

 

 start++;

 end--;

}

4. 输出结果


if (isPalindrome)

 cout << "Yes" << endl;

else

 cout << "No" << endl;

完整代码如下:


#include <iostream>

using namespace std;

int main() {

 string str;

 cin >> str;

 int start = 0;

 int end = str.length() - 1;

 bool isPalindrome = true;

 while (start < end) {

  if (str[start] != str[end])

   isPalindrome = false;

   break;

  

  start++;

  end--;

 }

 if (isPalindrome)

  cout << "Yes" << endl;

  else

  cout << "No" << endl;

 

 return 0;

}

  
  

评论区

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