C ++如何从字符串数组中删除标点符号?

问题描述

在下面显示的以下程序中,我尝试使用ispunct删除字符串数组中的所有标点符号

std::string fileName;
std::fstream readFile;
const int arraySize = 50000;
std::string storeFile[arraySize];

int main(int argc,char *argv[]){

for (int i = 0,len = storeFile[i].size(); i < len; i++) {  
 
if (ispunct(storeFile[i])){//check whether parsing character is punctuation or not
          
storeFile[i].erase(std::remove_if(storeFile[i].begin(),storeFile[i].end(),::ispunct),storeFile[i].end());
    
            }     
        }
}

但是我收到ispunct(storeFile[i]

的以下错误消息

function "ispunct" cannot be called with the given argument list -- argument types are: (std::string)

我以前在std :: string上使用过ispunct,但没有在std :: string数组中使用[]。如何从字符串数组中删除标点符号和空格?谢谢

 for (int i = 0; i < arraySize; i++)
    {
        while (readFile >> storeFile[i])
        {
            std::transform(storeFile[i].begin(),storeFile[i].begin(),::tolower);

            for (auto &s : storeFile)
            {
                s.erase(std::remove_if(s.begin(),s.end(),s.end());
                s.erase(std::remove_if(s.begin(),::isspace),s.end());
            }


             }
        }
        

解决方法

ispunct以1个字符作为输入,而不是整个字符串。

但是在删除标点符号之前,您不需要检查字符串。像这样简单的事情会起作用:

    for (auto& s : storeFile) {
        s.erase(std::remove_if(s.begin(),s.end(),::ispunct),s.end());
    }

Live demo

== EDIT ==

您有50000个字符串的固定数组。如果输入文件包含N个字符串,则将在其后打印50000-N个空行。这可能不是您想要的。请改用std::vector<std::string>

    std::string s;
    std::vector<std::string> storeFile;
    while (readFile >> s) {
        std::transform(s.begin(),s.begin(),::tolower);
        s.erase(std::remove_if(s.begin(),s.end());
        s.erase(std::remove_if(s.begin(),::isspace),s.end());
        storeFile.push_back(std::move(s));
    }
,

对于C ++ 20,它实际上只有一行代码:

考虑您有一个字符串str

std::erase_if(vec,ispunct);