c++ - 如何忽略空格和标点符号?

标签 c++ string palindrome

我写了一个回文检查器函数,它在大多数情况下都有效,但如果空格或标点符号不在字符串的中间,它就说它不是回文。

第一次测试:

Enter string to test for palindrome:

hannah

string is a palindrome.

第二次测试:

Enter string to test for palindrome:

han nah

string is a palindrome.

第三个测试:

Enter string to test for palindrome:

hann.ah

string is not a palindrome.

第四次测试:

Enter string to test for palindrome:

han.nah

string is a palindrome.

我想知道是否有一种方法可以同时忽略空格和标点符号,以便将 h.annahhann ah 视为回文?

这是我的代码:

void isPalindrome (string s){  
    if(equal(s.begin(), s.begin() + s.size()/2, s.rbegin()) )
        cout << "string is a palindrome. " << endl;
    else
        cout << "string is not a palindrome. " << endl;
}

int main(){
    string test1;
    cout << "Enter string to test for palindrome: " << endl;
    getline(cin, test1);

    isPalindrome(test1);

    string test2;
    cout << "Enter string to test for palindrome: " << endl;
    getline(cin, test2);

    isPalindrome(test2);

    string test3;
    cout << "Enter string to test for palindrome: " << endl;
    getline(cin, test3);

    isPalindrome(test3);

    return 0;
}   

最佳答案

在回文检查之前对字符串应用过滤器。

这是一种方法。

#include <string>
#include <iostream>
#include <algorithm>

void isPalindrome (std::string s){  
    if(equal(s.begin(), s.begin() + s.size()/2, s.rbegin()) )
        std::cout << "string is a palindrome. " << std::endl;
    else
        std::cout << "string is not a palindrome. " << std::endl;
}

std::string remove_rubbish(std::string s)
{
    auto is_rubbish = [](char c) 
                { 
                    return std::ispunct(c) || std::isspace(c); 
                };

    s.erase(std::remove_if(s.begin(), 
                           s.end(), 
                           is_rubbish), 
            s.end());

    return s;    
}

int main(){
    auto s= std::string("ha-n.n?a h");
    isPalindrome(remove_rubbish(s));

    return 0;
}   

关于c++ - 如何忽略空格和标点符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46834492/

相关文章:

c++ - Qt。如何处理双击事件

Java字符串实习生和文字

c++ - 搜索 "$"在 C++ 中返回错误

java - 反转整数以检查回文数

C++ 递归和指针问题

c++ - 函数调用缺少参数列表

c++ - 运营商评价

c++ - clang++ C++0x std::locale

C 检查数组中是否存在空间,如果不存在则重新分配更多空间?

java - System.out.println不是打印输出吗?