[英]C++ how to remove puncuation from a string array?
在下面顯示的以下程序中,我嘗試使用 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].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
需要 1 個字符作為輸入,而不是整個字符串。
但是您不需要在刪除標點符號之前檢查字符串。 像這樣簡單的事情會起作用:
for (auto& s : storeFile) {
s.erase(std::remove_if(s.begin(), s.end(), ::ispunct), s.end());
}
==編輯==
您有一個包含 50000 個字符串的固定數組。 如果輸入文件包含 N 個字符串,您將打印后跟 50000-N 個空行。 這可能不是你想要的。 改用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));
}
使用 C++20,它實際上只是一行代碼:
考慮你有一個字符串str
:
std::erase_if(vec, ispunct);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.