21xrx.com
2024-12-22 23:27:25 Sunday
登录
文章检索 我的文章 写文章
C++编程:判断输入的字符串是否为回文
2023-06-30 02:16:09 深夜i     --     --
C++ 编程 字符串 回文

C++ programming: Determining whether a given string is a palindrome

Palindrome is a word, phrase, or sequence that reads the same backward as forward. For example, the words "civic" and "deified" are palindromes. In programming, we can use various techniques to determine whether a given string is a palindrome. In this article, we will use C++ to demonstrate how to write a program that checks if a given string is a palindrome.

The solution to this problem is simple. We just need to compare the first and last characters of the string, then move inward. If the characters match, we continue. Otherwise, we can immediately declare the string is not a palindrome. This process can be done with a loop. A "for" loop is ideal for this type of task because the length of the string is needed for the loop condition.

Here is the C++ function that checks whether a string is a palindrome:


bool isPalindrome(string s) {

  int len = s.length();

  for(int i=0; i<len/2; i++) {

    if(s[i] != s[len-i-1])

      return false;

    

  }

  return true;

}

The variable "len" is assigned the length of the input string. We then use a "for" loop and loop through only half of the string. Then, we compare the "i-th" and "length-i-1-th" characters, where "i" is current loop iteration. If the two characters differ, we know the string is not a palindrome and return false. If the "for" loop completes without returning false, then the function returns true.

We can test this function using the following code:


int main() {

  string input;

  cout << "Enter a string: ";

  cin >> input;

  if (isPalindrome(input))

    cout << input << " is a palindrome.";

   else

    cout << input << " is not a palindrome.";

  

  return 0;

}

First, the user inputs a string. Then, we call the "isPalindrome" function with the input string as the argument. If the function returns true, the program prints "input is a palindrome." Otherwise, the program prints "input is not a palindrome."

In conclusion, determining whether a given string is a palindrome is a simple task that can be accomplished using C++ programming. The function presented in this article uses a "for" loop to compare characters starting from the beginning and end of the string. If the two characters differ, the function returns false. Otherwise, it returns true. By using this function, we can easily determine whether a given string is a palindrome or not.

  
  

评论区

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