简体   繁体   English

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

[英]C++ how to remove puncuation from a string array?

In the following program showed below I attempted to remove all puncuation from a string array using ispunct在下面显示的以下程序中,我尝试使用 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());
    
            }     
        }
}

However I recieve the following error on for ispunct(storeFile[i]但是我在ispunct(storeFile[i]

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

Ive used ispunct before for std::string but not a std::string array[].我之前对 std::string 使用过 ispunct 但没有对 std::string 数组 [] 使用过。 How can I remove puncuation and white space from a string array?如何从字符串数组中删除标点符号和空格? Thankyou谢谢

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

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


             }
        }
        

ispunct takes 1 character as input, not an entire string. ispunct需要 1 个字符作为输入,而不是整个字符串。

But you don't need to check the string before removing the punctuation.但是您不需要在删除标点符号之前检查字符串。 Something simple like this will work:像这样简单的事情会起作用:

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

Live demo现场演示

==EDIT== ==编辑==

You have a fixed array of 50000 strings.您有一个包含 50000 个字符串的固定数组。 If the input file contains N strings, you'll print that followed by 50000-N blank lines.如果输入文件包含 N 个字符串,您将打印后跟 50000-N 个空行。 It's probably not what you want.这可能不是你想要的。 Use std::vector<std::string> instead.改用std::vector<std::string>

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

With C++20, its actually just one line of code:使用 C++20,它实际上只是一行代码:

Consider you have a string str :考虑你有一个字符串str

std::erase_if(vec, ispunct);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM