【问题标题】:C++ Replacing non-alpha/apostrophe with spaces in a stringC ++用字符串中的空格替换非字母/撇号
【发布时间】:2014-04-13 08:45:38
【问题描述】:

我正在读取一个文本文件并将这些单词解析为一个映射,以计算每行中每个单词的出现次数。我需要忽略除撇号之外的所有非字母字符(标点符号、数字、空格等)。我可以使用以下代码弄清楚如何删除所有这些字符,但这会导致错误的单词,例如“one-two”出现为“onetwo”,应该是两个单词,“one”和“two”。

相反,我现在尝试用空格替换所有这些值,而不是简单地删除,但不知道如何做到这一点。我认为 replace-if 算法将是一个很好的算法,但无法找出正确的语法来完成此操作。 C++11 没问题。有什么建议吗?

示例输出如下:

"first second" = "first" and "second"
"one-two" = "one" and  "two"
"last.First" = "last" and "first"
"you're" = "you're"
"great! A" = "great" and "A"

// What I initially used to delete non-alpha and white space (apostrophe's not working currently, though)

// Read file one line at a time
while (getline(text, line)){
    istringstream iss(line);            
    // Parse line on white space, storing values into tokens map
    while (iss >> word){
        word.erase(remove_if(word.begin(), word.end(), my_predicate), word.end());
        ++tokens[word][linenum];
    }
    ++linenum;
}

bool my_predicate(char c){
    return c == '\'' || !isalpha(c); // This line's not working properly for apostrophe's yet
}

【问题讨论】:

    标签: string c++11 replace


    【解决方案1】:
    bool my_predicate(char c){
        return c == '\'' || !isalpha(c);
    }
    

    您在此处写道,如果 它是 和撇号,或者如果 它不是 字母字符,则要删除该字符。

    既然你想替换这些,你应该使用std::replace_if()

    std::replace_if(std::begin(word), std::end(word), my_predicate, ' ');
    

    你也应该更正你的谓词:

    return !isalpha(c) && c != '\'';
    

    【讨论】:

      【解决方案2】:

      您可以使用std::replace_if 在将输入行发送到 istringstream 之前对其进行预处理。这也将简化您的内部循环。

      while (getline(text, line)){
          replace_if(line.begin(), line.end(), my_predicate, ' ');
          istringstream iss(line);            
          // Parse line on white space, storing values into tokens map
          while (iss >> word){
              ++tokens[word][linenum];
          }
          ++linenum;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-04
        • 2015-07-16
        • 2016-06-17
        • 1970-01-01
        • 1970-01-01
        • 2010-12-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多