如何从char数组中删除标点符号?

时间:2014-03-05 05:15:10

标签: c++ arrays string visual-studio char

我的程序提示用户输入一个短语来检查它是否是一个回文,那么它应该打印出没有大写的短语或者像'',?等特殊字符。我的问题是删除这些字符。我已经得到了程序忽略它们我问我应该如何删除它们?我发表评论,我认为该声明应该去。示例输出应该是:“Madam I'm Adam”to“madamimadam”

#include <iostream>
#include <string>
#include <cctype>
    using namespace std;

int main()
{
    //Variables and arrays
    int const index = 80;
    char Phrase[index];
    char NewPhrase[index];
    int i, j, k, l;
    bool test = true;

    //Prompt user for the phrase/word
    cout << "Please enter a sentence to be tested as a palindrome: ";
    cin.getline(Phrase, 80);

    //Make everything lowercase, delete spaces, and copy that to a new array 'NewPhrase'
    for(k = 0, l = 0; k <= strlen(Phrase); k++)
    {
        if(Phrase[k] != ' ')
        {
            NewPhrase[l] = tolower(Phrase[k]);
            l++;
        }
    }
    //cout << "The Phrase without punctuation/extra characters: " << newPhrase[l];

    int length = strlen(NewPhrase); //Get the length of the phrase

    for(i = 0, j = length-1; i < j; i++, j--)
    {
        if(test) //Test to see if the phrase is a palindrome
        {
            if(NewPhrase[i] == NewPhrase[j])
            {;}
            else
            {
                test = false;
            }
        }
        else
            break;
    }

    if(test)
    {
        cout << endl << "Phrase/Word is a Palindrome." << endl << endl;
        cout << "The Palindrome is: " << NewPhrase << endl << endl;
    }
    else
        cout << endl << "Phrase/Word is not a Palindrome." << endl << endl;

    system("Pause");
    return 0;
}

2 个答案:

答案 0 :(得分:3)

修改此行:

if(Phrase[k] != ' ')

成为:

if((phrase[k] != ' ') && (ispunct(phrase[k]) == false))

这意味着我们会同时检查空格和标点符号。


另外,请考虑改写:

if(NewPhrase[i] == NewPhrase[j])
        {;}
        else
        {
            test = false;
        }

这样:

if(NewPhrase[i] != NewPhrase[j])
   test = false;

答案 1 :(得分:2)

这是建议:

  1. 使用std::string
  2. 使用std::ispunct确定字符串中的字符是否为标点符号
  3. 使用erase-remove idiom删除标点符号
  4. 这是一行代码(加上一条方便lambda的额外行):

    std::string phrase = .....;
    
    auto isPunct = [](char c) { return std::ispunct(static_cast<unsigned char>(c)); }
    
    phrase.erase(std::remove_if(phrase.begin(), phrase.end(), isPunct), 
                 phrase.end());
    

    接下来,从my answer to this recent question转换为小写,另一个单行:

    std::transform(phrase.begin(), phrase.end(), phrase.begin(),
                   [](char c)
                   { return std::tolower(static_cast<unsigned char>(c));});