首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从字符串中删除标点符号

如何从字符串中删除标点符号
EN

Stack Overflow用户
提问于 2015-02-16 02:43:23
回答 3查看 164关注 0票数 0

我正在寻求帮助,在代码中读取包含标点符号的字符串,并输出用省略标点符号读取的内容。我访问了这个链接C++ Remove punctuation from String,我相信我的代码是可靠的。当我编译代码时,它会提示输入字符串。然而,在输入字符串并按enter之后,什么都没有发生

代码语言:javascript
运行
复制
int main(){
    string line;
    cout <<"Please Enter a line"<< endl;
    while(getline(cin, line)){
        for(decltype(line.size()) index = 0; index != line.size() && !isspace(line[index]); ++index){        
            if (ispunct(line[index])){
                line.erase(index--,1);
                line[index] = line.size();
            }
        }
    }
    cout<< line << endl;
    return 0;
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-02-16 02:52:44

你让这条路变得更复杂了(decltype?为了这个?)比它所需要的要多。尝试:

代码语言:javascript
运行
复制
int main()
{
    std::string line;
    std::cout <<"Please Enter a line"<< std::endl;
    while(std::getline(std::cin, line)){
        const char* s = line.c_str();
        while(*s){
            if (!ispunct(*s)){
                std::cout << *s;  // not as slow as you would think: buffered output
            }
            ++s;
        }
        std::cout << std::endl; // flush stdout, that buffering thing
    }
}

更简单通常更好。作为一个额外的奖励,这也应该是相当快一些。

票数 1
EN

Stack Overflow用户

发布于 2015-02-16 03:25:58

这可以在没有循环的情况下完成。使用算法函数是您所需要的。

通常,如果您有一个容器,并且您希望从满足某种条件的容器中删除项,那么如果您正在编写手工编码的循环,那么您将使用一种长的(可能是错误的)方法。

下面是一个使用算法函数的示例,即std::remove_if

代码语言:javascript
运行
复制
#include <algorithm>
#include <cctype>
#include <string>
#include <iostream>

using namespace std;

int main()
{
   std::string s = "This is, a, string: with ! punctuation.;";
   s.erase(std::remove_if(s.begin(), s.end(), ::ispunct), s.end());
   cout << s;
}

实例:http://ideone.com/Q6A0vJ

票数 0
EN

Stack Overflow用户

发布于 2015-02-16 03:17:34

您的代码没有输出任何东西的原因是因为它被困在getline循环中。

假设c++11:

代码语言:javascript
运行
复制
int main(){
  string line;
  cout <<"Please Enter a line"<< endl;
  getline(cin, line);
  line.erase(std::remove_if(line.begin(),  line.end(),  
               [](char ch) { return ispunct(ch) ? true : false; }), line.end());
  cout << line << endl;
  return 0;
}

代码语言:javascript
运行
复制
int main(){
  string line;
  cout <<"Please Enter a line"<< endl;
  transform(line.begin(), line.end(), line.begin(), 
              [](char ch) {  return ispunct(ch) ? '\0' : ch; });
  cout << line << endl;
  return 0;
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28533819

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档