Topic:
Writing functions
int Palindrom (char *string);
If the argument string is a palindrome, the function returns True, otherwise it returns false. A palindrome is the same as a string that reads from left to right and is read from one to the left. The function should ignore all non-alphabetic characters and do not have to be case sensitive for character comparisons.
The premise is that whitespace characters, punctuation, and case states are ignored, and when Adam encounters Eve for the 1th time, he may say: "Madam,i ' Adam" is a palindrome.
Analysis of the topic, the title does not specify whether the empty string and all non-alphabetic characters are palindrome, I privately put the empty string into a palindrome, all non-alphabetic characters are classified as non-palindrome, the Palindrom function encoding implementation of the following ideas:
- When strlen (string) <= 1. Returns true if the length of string is 0, or true if the length of string is 1, or false if it is an alphabetic character.
- When strlen (String) >=2.
Use the pointer p to point to the end of the string, from both ends (the string pointer from front to back, the P pointer from the back forward) to compare the alphabetic characters, *string and *p in the case of both alphabetic characters, either an equality relationship, or a case relationship, and immediately return FALSE if the palindrome condition is not met.
Write the code as follows and pass the test using "madam,i m Adam".
1#include <iostream>2#include <string.h>3 Const Static intBuff_size = -;4 BOOLPalindrome (Char*str);5 intMainintargcChar*argv[])6 {7 CharStr[buff_size];8std::cout<<"Enter a char[]:"<<Std::endl;9 std::cin.getline (str, buff_size);Tenstd::cout<<"Str:"<<str<<Std::endl; One if(Palindrome (str)) A { -std::cout<<"\""<<str<<"\ "is a palindrome\n"; - } the Else - { -std::cout<<"\""<<str<<"\ "is not a palindrome\n"; - } + return 0; - } + BOOLPalindrome (Char*str) A { at if(strlen (str) = =0) - { -std::cout<<"It is a null string\n"; - return true; - } - if(strlen (str) = =1) in { - if(Isalpha (*str)) to { + return true; - } the Else * { $std::cout<<"it has no alpha\n";Panax Notoginseng return false; - } the } + Char* p =str; A while(' /'!= *(++p)) the { + //p++; - } $p--; $ while(Str <p) - { - while(!isalpha (*str)) the { - if(' /'== *str)Wuyi { thestd::cout<<"it has no alpha\n"; - return false; Wu } -++str; About } $ while(!isalpha (*p)) - { ---p; - } A if(Islower (*str)) + { the if((*p = = *str) | | (*p = = *str- +)) - { $++str; thep--; the } the Else the { - return false; in } the } the Else About { the if((*p = = *str) | | (*p = = *str + +)) the { the++str; +--p; - } the ElseBayi { the return false; the } - } - } the}
C and pointers--programming question 9.14 Section 10 small question--judging palindrome function