回文写法
测试字符串是否是回文字串
1. bool is_palindrome(char *str, int size) 2. { 3. int tmp1 = size-2, tmp2 = (size-1)/2; 4. for (int i = 0; i < tmp2; ++i) 5. { 6. if (str[i] != str[tmp1-i]) 7. return false; 8. } 9. return true; 10. }
然后,不管对应位置的大小写:
可以这么写:
# bool is_palindrome(char *str, int size) # { # int tmp1 = size-2, tmp2 = (size-1)/2; # for (int i = 0; i < tmp2; ++i) # { # int char_dif = str[i]-str[tmp1-i]; # if (str[i] == str[tmp1-i] || abs(char_dif)==32) # continue; # return false; # } # return true; # }
忽略源字符串内的标点符号,测试是否是回文串:
# #include <iostream>
# #include <iostream>
# #include <math.h>
# using namespace std;
#
#
# struct res
# {
# char *s;
# int size;
# };
# res ignore_punctuate(char *str, int size)
# {
# int tmp = size-2;
# char *str1 = new char[size];
# int j = 0;
# for (int i = 0; i <= tmp; ++i)
# {
# if (!ispunct(str[i]))
# {
# str1[j++]=str[i];
# }
# }
# str1[j]='\0';
# res tmp1;
# tmp1.s = str1;
# tmp1.size=j+1;
# return tmp1;
# }
# bool is_palindrome(char *str, int size)
# {
# int tmp1 = size-2, tmp2 = (size-1)/2;
# for (int i = 0; i < tmp2; ++i)
# {
# int char_dif = str[i]-str[tmp1-i];
# if (str[i] == str[tmp1-i] || abs(char_dif)==32)
# continue;
# return false;
# }
# return true;
# }
#
# int main()
# {
# char a[]="abb,A";
# int size = sizeof(a)/sizeof(*a);
# res tmp = ignore_punctuate(a,size);
# cout << is_palindrome(tmp.s, tmp.size) << endl;
# }